On Demand Loading of JavaScript and CSS files

By Akbar

In just few years period, there has been a transition of websites from the standalone information soils to responsive and connected platforms which looks more like a desktop application to the user in working. Though this has increased the overall usability of the websites (at least for majority of sites), as a web programmer, one of the major problem of this transition is that it has increased the resource’s size (HTML, JavaScript, CSS) which are downloaded to the user machine before a page is displayed and this has increased the load time of the pages. With more and more dynamic websites (heavily using AJAX and DHTML), usually the size of the JavaScript (and to some extent of the CSS) files is nearly 2-8 times the size of the main HTML file. So, if we force download the JavaScript and CSS files during the page load, then it will increase the overall load and display time for the page. Of course, there has been improvements in the Internet speed too, but believe me some of people (may be still a majority in 3rd world countries) still rely on the old dial-up connections for browsing the web. So, if one has multiple JavaScript and CSS files (and which is most of the time a good practice), then it would be good to load these files on the demand.

Enough talking about the requirements, let’s quickly jump to the solutions. Here are some possible options:

1. We can use the Document.Write to render the Script and Link tags during the page load. Some of you may say, “Hey, this is not on-demand loading. This is just a selective loading, as the documents will be still loaded during page load.”. I agree that it’s not on-demand loading. But guess what; I was thinking that some of you guys may post this in comments as an alternative, so I thought to discuss and block this in the start. Am I being over smart? 🙂

2. The second (and actually the first) option is to use the AJAX (XMLHTTPResponse object) to read the java-script file and then render its content using the JavaScript’s eval function. This way not only one can execute the JavaScript files, but can also execute JavaScript statements after an AJAX action update some of the UI objects. I am sure you have guessed by now that this is the technique used by most of the AJAX framework libraries on client side. You can read more about this at:
http://ajaxpatterns.org/On-Demand_Javascript

3. The second (again second?), my favorite and comparatively less used option is to use the JavaScript to build the correct SCRIPT (for JavaScript import) and LINK for CSS import) elements and then add those to document DOM (Isn’t it what’s called DHTML?). Here are the two sample scripts I use for this purpose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Load the given JavaScript file. This function is good for on-demand loading and when
// loading files based on the AJAX response
function ImportJavaScript(sourceUrl)
{
	// The basic script is simple, create the SCRIPT object and add it to HTML DOM
	var scriptElem = document.createElement('script');
	scriptElem.src = sourceUrl;
	scriptElem.type = 'text/javascript';
 
	// Append this to header object
	document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
 
// Load the given CSS file. This function is good for on-demand CSS loading
function ImportCss(sourceUrl)
{
	// First check if we browser can directly load the CSS file
	if(document.createStyleSheet)
		document.createStyleSheet(sourceUrl);
	else
	{
		// Load the CSS using the DHTML (create Link tag and add it to header)
		var linkElem = document.createElement('link');
		linkElem.rel='stylesheet';
		linkElem.type = 'text/css';
		linkElem.href = sourceUrl;
 
		// Append this to header object
		document.getElementsByTagName("head")[0].appendChild(linkElem);
	}
}

So whererver you need to load a JavaScript or CSS file in your code, you can do something like this:

1
2
ImportJavaScript(/Library/XYZ/MyJavaScript.js);
ImportJavaScript(/CSS/AddPanel.css);

That’s it. If you are thinking that’s it, then you are mising one important questions you will be soon asking as soon as you are done with adding this function. The question is “How I will know that Browser has downloaded the required JavaScript file”. Hmm… good question. Well, there is no direct way of finding this out (or at least I don’t know). What I do is that I append a dummy function at the end of my JavaScript file and then keep checking if it’s valid, something like

1
2
3
4
if (MyJavaScriptFileLoaded)
	alert("Yes, it's loaded");
else
	alert("Still loading...");

That’s all about on demand loading of JavaScript and CSS files. This way you can just load the necessary JavaScripts file (of course the one containging the above two functions) and cut down you first page load and display time.

Tags: , , ,