ensure: on demand resources
Date : 2008 06 12 Category : Tech & DevelopmentOmar AL Zabir of Pageflakes.com has posted on ensure, his JavaScript library that provides a handy function ensure which allows you to load JavaScript, HTML, CSS on-demand and then execute your code.
Ensure ensures that relevant JavaScript and HTML snippets are already in the browser DOM before executing your code that uses them.
For example:
PLAIN TEXT JAVASCRIPT:ensure( { js: "Some.js" }, function() { SomeJS(); // The function SomeJS is available in Some.js only });
You can also specify multiple Javascripts, html or CSS files to ensure all of them are made available before executing the code:
PLAIN TEXT JAVASCRIPT:ensure( { js: ["blockUI.js","popup.js"], html: ["popup.html", "blockUI.html"], css: ["blockUI.css", "popup.css"] }, function() { BlockUI.show(); PopupManager.show(); });
Omar says:
Websites with rich client side effects (animations, validations, menus, popups) and Ajax websites require large amount of Javascript, HTML and CSS to be delivered to the browser on the same web page. Thus the initial loading time of a rich web page increases significantly as it takes quite some time to download the necessary components. Moreover, delivering all possible components upfront makes the page heavy and browser gets sluggish responding to actions. You sometimes see pull-down menus getting stuck, popups appearing slowly, window scroll feels sluggish and so on.
The solution is not to deliver all possible HTML, Javascript and CSS on initial load instead deliver them when needed. For example, when user hovers the mouse on menu bar, download necessary Javascript and CSS for the pull-down menu effect as well as the menu html that appears inside the pull-down. Similarly, if you have client side validations, deliver client side validation library, relevant warning HTML snippets and CSS when user clicks the 'submit' button. If you have a Ajax site which shows pages on demand, you can load the Ajax library itself only when user does the action that results in an Ajax call. Thus by breaking a complex page full of HTML, CSS and Javascript into smaller parts, you can significantly lower down the size of the initial delivery and thus load the initial page really fast and give user a fast smooth browsing experience.
There is a detailed writeup on how it all works, and it dovetails with the recent performance proposals around when to download resources (sometimes you may not want to wait for on demand loading of course).