JavaScript Patterns

Page 221

Lazy-Loading The technique known as lazy-loading refers to loading an external file after the page load event. It’s often beneficial to split a large bundle of code into two parts: • One part that is required for the page to initialize and attach event handlers to the UI elements • A second part that is only needed after user interaction or other conditions The goal is to load the page progressively and give the use something to work with as soon as possible. Then the rest can be loaded in the background while the user is engaged and looking around the page. The way to load the second part of the JavaScript is again to simply use a dynamic script element appended to the head or the body: ... The full body of the page ... <!-- end of chunk #2 --> <script src="all_20100426.js"></script> <script> window.onload = function () { var script = document.createElement("script"); script.src = "all_lazy_20100426.js"; document.documentElement.firstChild.appendChild(script); }; </script> </body> </html> <!-- end of chunk #3 -->

For many applications, the lazy part of the code will most often be bigger than the core part, because the interesting “action” (such as drag and drop, XHR, and animations) happens only after the user initiates it.

Loading on Demand The previous pattern loaded additional JavaScript unconditionally after page load, assuming that the code will likely be needed. But can we do better and load only parts of the code and only the parts that are really needed? Imagine you have a sidebar on the page with different tabs. Clicking on a tab makes an XHR request to get content, updates the tab content, and animates the update fading the color. And what if this is the only place on the page you need your XHR and animation libraries, and what if the user never clicks on a tab? Enter the load-on-demand pattern. You can create a require() function or method that takes a filename of a script to be loaded and a callback function to be executed when the additional script is loaded.

Loading Strategies | 203


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.