Right, with the rise of JavaScript frameworks the internet has become a richer communication medium. But at the same time, websites have become bigger and fatter in a sense. The reason for this a lot of the time is because if there’s a specific piece of functionality on a website, a jQuery plug-in is downloaded, added to the page template, left there and only really used 2 or 3 times throughout the entire website.
But really, is there any reason why this should happen? In some cases, this would make sense. Like if data or even entire pages are dynamically loaded via AJAX. But in reality, no, this doesn’t need to happen at all. It just shouldn’t happen.
The concept of lazy loading (or On-demand JavaScript) is simple. Only when code is needed on the page should it be loaded.
If one really had to take the time to think about it, on a page where non-user defined data is loaded using AJAX, this would qualify as a form of lazy loading. We wouldn’t load 20 pages worth of data into a page on load and use JavaScript to only show and hide certain pieces of the data when the user requests. It’d be very slow and could annoy the user. Therefore we use AJAX (XMLHTTPRequests) to load sections of data as needed. The question then is, why should we load all the JavaScript into a page, when it’s really only going to be used every now and then? Hence the reason for performing “AJAX” like tasks to load code only as it is needed.
By doing this, the bare minimum is loaded, which speeds up the page and makes it easy to maintain. Just as we wouldn’t expect a DBA to get involved in the wire framing and design process of a website, there’s no reason why technologies should be mixed either. CSS should always be created in a separate CSS file and then linked into the page. The same goes for JavaScript. But the question then comes down to, why is there just so much JavaScript in HTML files? By lazy loading files and automating the process in initializing events a thicker, more defined line is drawn between the structural layer and the functional layers of the UI. This leads to a much cleaner, much easier to maintain and slimmer website.
The simplest way to achieve this is to create some code in JavaScript and simply set triggers to call a function that will load data into the page when needed. A simple file that can perform this task can be downloaded from the ‘playground’.