Lazy loading with Javascript and Firefox

Lazy loading has been a hot topic highly discussed over the internet recently. The amount of bandwidth for the average user has grown tenfold during the last few years, but the web itself has evolved a lot, and so have the contents of the temp folder.

This has created a need to dynamically load a piece of script (to make the host machine download it), instead of just forcing the user download everything from the very first load.

Javascript is a great language and its power has yet to be fully exploited by developers, but from some points of view it sometimes lacks basic capabilities, one of which is lazy loading.

While browsing the internet, I’ve discovered a lot of great articles on the matter, with examples and everything, but the solutions provided don’t apply at all times, like for example when developing Firefox extensions.

The main approach that seems to be popular among developers is inserting an extra “script tag” inside the head element of the page at some point in the code, by first extracting the head via a:

document.getElementById(“head”)[0]

statement, creating a new text node via

document.createTextNode

(which contains the exact “<script></script>” declaration) and appending it via

document.appendChild

I won’t go into more detail on this solution, a couple of searches on the matter will sort anything you might have not understood so far.

While elegant, the approach doesn’t cut it in some cases.  For example, while developing the Silentale Firefox Extension, I was struggling to load jQuery “later” than usual, because loading it in the same place as all of my other scripts was breaking the Firefox UI. Well, the problem is that in an overlay file there’s no such thing as a “head” element to append children to, so I was stuck.

After almost a day of researching, I came across the following solution which works seamlessly everywhere:

var scriptLoader = Components.classes[@mozilla.org/moz/jssubscript-loader;1].getService(Components.interfaces.mozIJSubScriptLoader);
scriptLoader.loadSubScript(path, context);

This code obtains a reference to the actual Firefox subscript loader component inside the “scriptLoader” variable and calls the loadSubScript method.

The loadSubScript method takes two parameters: the first one is the string path to the javascript source file to load, and the second one is the context of where to load the script (by default the current document object). Using the second parameter is great for loading code inside a particular scope, so don’t miss out on it.

These two lines of code would have solved a lot of problems for me if I had known of their existence earlier. Hopefully they will do the same for you.

Have fun coding :)

Your comment: