Wiki source code of Lazy Loading

Version 1.2 by Marius Dumitru Florea on 2021/08/24

Hide last authors
Marius Dumitru Florea 1.1 1 One common and recurrent need when working on the front-end is to be able to load some UI elements after the page has been loaded. This technique is called lazy loading and it's very useful if you have UI elements that don't need to be visible right away, especially if they are heavy and thus would slow down the page load. We use this for instance to:
2
3 * load the content of a modal dialog box on demand, when the modal is first shown
4 * load the content of a tab when the tab is first activated
5 * load the content of a panel after the rest of the page has been loaded
6
7 In order to apply this technique you need to have:
8
Marius Dumitru Florea 1.2 9 * a JavaScript code that makes an asynchronous HTTP request to get the UI element that is being lazy loaded
Marius Dumitru Florea 1.1 10 * a server side script / service that generates and returns the HTML of the requested UI element
11
12 The JavaScript code usually looks like this:
13
14 {{code language="js"}}
15 //
16 {{/code}}
17
18 Note that triggering the ##xwiki:dom:updated## event is very important because it allows the loaded UI element to be enhanced by other JavaScript modules (some of which may have been also lazy loaded along with the UI element). {{version since="13.7-rc-1"}}Note also that we don't have to care about loading / injecting the JavaScript or CSS required by the UI element. This is done automatically by the XWiki platform, with the help of the server side, as we'll see below.{{/version}}
19
20 A JavaScript module that enhances UI elements that are being lazy loaded looks like this:
21
22 {{code language="js"}}
23 //
24 {{/code}}
25
26 For the server side we use most of the time:
27
28 * either a script rendering macro (e.g. [[Velocity Macro>>extensions:Extension.Velocity Macro]]) within a wiki page(((
29 {{code language="js"}}
30 //
31 {{/code}}
32 )))
33 * or a Velocity template(((
34 {{code language="js"}}
35 //
36 {{/code}}
37 )))
38
39 If we chose to implement the server side in a wiki page using the Velocity macro then the code could look like this:
40
41 {{code language="none"}}
42 ##
43 {{/code}}
44
45 The resources we specify using the ##X-XWIKI-HTML-HEAD## custom HTTP header will be injected automatically in the page head.

Get Connected