Loading the on-demand JavaScript and CSS the YUI way
Web 2.0 applications relies on heavy JavaScript resources that may slow down the page loading time, which in turn results in unhappy end users. This article explains lazy loading techniques of JavaScript/CSS using YUI Get utility through which you can make the page loading much faster.
This article will explain the concept of lazy loading of resources in a page and how the javascript or CSS resources can be loaded dynamically using the YUI framework.
The problem
In Web 2.0 era the applications started to use JavaScript functionalities more and more in it for eg: Google Maps, GMail, Yahoo! Mail, etc. Each page supports large number of different functionalities based on JavaScript that consists of different JavaScript resources (source files).
Depends upon the features the pages provides the size of the JavaScript resources started to grow. We have some methods using which we can reduce the size of the JavaScript code for eg: Minifying JavaScript or CSS, GZipping the minified resources. Most of the popular browsers supports uncompression of compressed resources automatically during the page loading.
If you try to load a large number of script nodes through script tags in your page there is very high chance of getting a web page that under perform during the user access. Why it is so?
Browsers tend to download the page components parallely. As you figured this nature will definitely improve the page loading. But this is not the case of script tags, more precisely the browser leaves its parallel downloading capabilities when it start to download the external scripts that comes as a part of the script tags. So if page contains large number script tags that loads large JavaScript resources, there is higher chances slowing the page loading.
The situation worsen especially if the developer tries to load the external javascript resources as a part of the head of the web page. This will result in a blank page until all the script resources loads in the browser completely, which the website user may not find very funny.
The Solution
Fortunately for developers there are number of solutions available through which we'll be able to make the page loading faster. I will explain them in a one by one manner here
SCRIPT tag placements
If you are using heavy external script resources then it would be better if you avoid script tags from the head section of the HTML page. Instead you can put them as the last part of page's body section.
If you think this logically you'll be able to see it without much difficulty. Since the first script tag comes after the last meaningful HTML element in the page, the user will be able to view the whole page content when the browser starts to download the first script resource. In other words in this method the script tags will not be able to block the page content loading.
This approach is useful especially when you are working with heavy JavaScript resources.
This is not the case with CSS resources. You can load your CSS files as a part of the head section. This is necessary because otherwise the content in the body section of the page that uses the CSS will not display properly. You can minimize your CSS and load them as a part of the head section of the page.
Lazy/On-demand Loading
Lazy loading (On-demand loading) is a technique through which the developer will split up the script resources and find out the script chunks needed to complete the page loading.
In other words the developer will load the most required JavaScript resources during the initial page loading. The remaining part will be loaded as and when they are required or as a part of the DOM loading completion. You will be able to find out the most necessary JavaScript methods you use while loading the page using Firebug's profile (check the Profile JavaScript performance section) feature.
In this technique a developer will try to avoid the usage of static script tags in the page as much as possible. It is not possible to avoid them completely. if you use JavaScript then at least one of the static script tag will be there in your page.
YUI 3
The revolutionary framework from Yahoo!. This is still in its infancy stage (If you are looking for a mature framework with lots of widgets, control, utility, etc then check YUI 2). YUI 2 and 3 provides the following utilities:
We can avoid YUI Loader utility from here itself as it is specifically used for loading YUI components as and when they are needed. This utility can't be used to loading custom script resources.
Dynamic Loading using YUI Get
Using YUI Get utility the developer will be able to load the script and CSS nodes in page's DOM easily. In order to use the YUI Get utility in your page you need to include a script tag in your body section and the src attibute value to the following value:
http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js
The above script tag will download the yui framework file from Yahoo!'s server directly. If you don't want to use this approach you can download the YUI 3.0 framework here and use a localized yui-min.js file with your own custom path information with the file.
Note that by including this file you'll be able to use other components supported by the YUI framework in your page. But that topic is beyond the scope of this article.
Lets start with some example code that demonstrates the script node insertion dynamically.
var tid = YUI().Get.script("jscode/gallery.js");
The above code is the bare minimum code that you needs to include a script resource in a page dynamically using YUI Get utility. This will dynamically inserts a script node in the currently loaded DOM and returns a string object containing info about the transaction.
Here is a sample code for dynamically loading a CSS resource using YUI Get utility
var tid = YUI().Get.css("css/gallery.css");
The real beauty of this utility comes with its configuration options that can be used while loading the script/css resources in the page. You can find a complete list of options here:
Script Options
onSuccess - callback function to execute when the script(s) are finished loading The callback receives an object back with the following data:
win - the window the script(s) were inserted into
data - the data object passed in when the request was made
nodes - an array containing references to the nodes that were inserted
purge - a function that, when executed, will remove the nodes that were inserted
onTimeout - callback to execute when a timeout occurs. The callback receives an object back with the following data:
win - the window the script(s) were inserted into
data - the data object passed in when the request was made
nodes - an array containing references to the nodes that were inserted
purge - a function that, when executed, will remove the nodes that were inserted
onEnd - a function that executes when the transaction finishes, regardless of the exit path
onFailure - callback to execute when the script load operation fails The callback receives an object back with the following data:
win - the window the script(s) were inserted into
data - the data object passed in when the request was made
nodes - an array containing references to the nodes that were inserted
purge - a function that, when executed, will remove the nodes that were inserted
context - the execution context for the callbackswin
- a window other than the one the utility occupies
autopurge - setting to true will let the utilities cleanup routine purge the script once loaded
purgethreshold - The number of transaction before autopurge should be initiated
data - data that is supplied to the callback when the script(s) are loaded.
insertBefore - node or node id that will become the new node's nextSibling.
charset - Node charset, default utf-8 (deprecated, use the attributes config)
attributes - An object literal containing additional attributes to add to the link tags
timeout - Number of milliseconds to wait before aborting and firing the timeout event
CSS options
onSuccess - callback to execute when the css file(s) are finished loading The callback receives an object back with the following data:
win - the window the link nodes(s) were inserted into
data - the data object passed in when the request was made
nodes - An array containing references to the nodes that were inserted
purge - A function that, when executed, will remove the nodes that were inserted
context - the execution context for the callbacks
win - a window other than the one the utility occupies
data - data that is supplied to the callbacks when the nodes(s) are loaded.
insertBefore - node or node id that will become the new node's nextSibling
charset - Node charset, default utf-8 (deprecated, use the attributes config)
attributes - An object literal containing additional attributes to add to the link tags
onSuccess, onFailure and onEnd callbacks of Script/CSS options
YUI Get utility accepts callback functions.
onSuccess callback function will be triggered when the resource loading operation is a success.
onFailure callback function will be triggered when the resource loading operations is a failure.
onEnd callback function will be triggered when the resource loading operation end irrespective of the transaction results.
The following is the code snippet that will execute some JavaScript code in the event of suceess or failure of resource loading
var options = {
onSuccess:function(){
alert("YUI Get loaded the script resource successfully"); //Here you can furnish whatever code that you want to execute after loading the script resource into the DOM.
},
onFailure:function(){
alert("YUI Get could not load the resource successfully");
}
};
var tid = YUI().Get.script("jscode/gallery.js", options);
If the transaction is success the onSuccess callback will be get executed otherwise onFailure callback
var options = {
onEnd:function(){
alert("I don't know whether the process is success or failure. But I'll be executed"); //Whatever may be the result the code furnished here will be executed.
}
};
var tid = YUI().Get.script("jscode/gallery.js", options);
Loading Multiple Resources
Loading a single resource at a time is simple and straight forward. But what about multiple resources. You can do that too using YUI Get utility. Here is an example for loading multiple CSS files, the same principle is applicable to the script resources except that you need to use YUI().Get.script for that:
var cssUrls = [
"css/gallery_1.css",
"css/gallery_2.css",
"css/gallery_3.css",
"css/gallery_4.css"
];
var options = {
onSuccess:function(){
alert("CSS resources loaded correctly in the DOM");
},
onFailure:function(){
alert("YUI Get could not load the resource successfully");
}
};
YUI().Get.css(cssUrls, options);
Related Links
Lazy Loading
On-Demand Pattern
YUI 3 Home
YUI Get Utility
Best Practices for Speeding Up Your Web Site
YUI Compressor for Minifying JavaScript/CSS
Gzipping Minified JavaScript
Nothing Found!
Why not submit your own content? Signup here.
-
Build A Free Ecommerce Store Front In Less Than An Hour | By AaronMeagher | in Web Development
Are you looking to start selling online and want a quick and easy solution for your ecommerce storefront? While yo...
-
Black Hat SEO Techniques | By ChandraK | in Web Development
Black hat SEO is a technique that is used to get higher ranking for the website in a base manner. Black hat SEO is ...
-
White Hat SEO Techniques | By ChandraK | in Web Development
White hat SEO is a method that follows all the required webmaster guidelines in effective building of the website. ...
-
Create a panoramic image slideshow in Dreamweaver | By extendstudio | in Web Development
In this tutorial we will make a moving panorama slideshow using Creative DW ImageshowPro and Dreamweaver. We will c...
-
Google Development and Google API Topics | By OGolden | in Web Development
Abundant information is available on Google Data API topics....
Nothing Found!
Why not submit your own content? Signup here.








No comments yet.