There is no easier way to optimise the download speed of a website than by lazy loading JavaScript files into the page as they are needed. This is even more useful when creating AJAX driven websites that load user defined data into a page.
But the drawback of using lazy loading is that as the website gets bigger, so the maintenance of the scripts becomes harder and can get very messy. So what we have here is something that I hope a lot of people would find very handy. It’s a very simple JavaScript object that ‘automates’ the process and keeps everything clean, organized and separate from the presentation layer.
The object contains a ‘Files’ array, this is where all the different script URLs are stored against a name which is easy to remember and used to call the script, an id, which is used to prevent duplicate scripts being loaded. A default Event Handler can be also which will be triggered once the script file has loaded.
E.g.
Files: [{ 'name': 'XHR', 'id': 'uniqueXHRID', 'url': '/somepath/XHR.js', 'fileHandler':'testMe()' }]
The ‘Init’ function is the initializing event for the script. This event must be passed an array of the names of the scripts that you would like to load. This is used to load script files that are stored within the ‘files’ array.
There is a separate object contained within the LazyJS object called ‘ScriptInit’. This object contains events that are used to initialize the scripts that have been loaded. This is very useful as it keeps all the events and file locations in one uniform place while keeping the footprint on the DOM to a minimum. This is never a bad thing.
There are two ways that this script can be run.
The first way to run this script is by passing an array containing the names or the files you wish to load into the page along with a custom Event Handler (if you don’t want to use the default for any reason).
E.g.
var run = [
{"name": "popup”},
{"name": "XHR", "scriptBlock": "testMe('cat')"}];
LazyJs.Init(run);
Or
LazyJs.Init(["name": "popup”]);
The third way this script could be used would more commonly be used to load single files into the page on the fly by simply calling the ‘Load’ function within the LazyJS object. This needs to be passed a URL and ID, optionally, an event can be passed in to be triggered once the file has been loaded. These parameters are all string values. The Event needs to be contained within the LazyJS object in the ‘ScriptInit’ object.
E.g.
LazyJS.Load('/somepath/XHR.js', 'uniqueXHRID', 'testMe()');
LazyJS.js - 1.12KB