There are multiple loading times, and each of them should be used wisely, in order to achieve the fastest loading times of your app.
- Scripts loaded within the <head> tag
- Scripts loaded at the bottom of the <body> tag
- Scripts loaded after window.onload event
- Scripts loaded on demand
Loading scripts within the <head> tag
Script files loaded in the <head> prevent the document body from rendering, which results in a blank page being displayed to the user while the browser waits to download and execute the script.
As such, most web applications will only load script files in the <head> if it’s absolutely necessary for the script to do its job – for instance, analytics software that tracks user behaviour needs to be loaded as early as possible in order to accurately track everything.
Loading scripts at the bottom of the <body> tag
This loading method is considered as one of the best practices in JS loading times. In this area you should include all of the scripts that are necessary to be on the page at the page load – for example JS libraries like jQuery.
The most important thing to remember about this loading time – make sure you load the bare minimum required code for functionality. any other code should be loaded on demand.
Loading scripts after window.onload event
The load event – is triggered after the HTML & JS within the <body> has finished loading & executing.
At this point the browser is no longer “busy”, and it would be a good time to load non core functionality code.
for example – chat widget, feedback form, etc…
In order to load scripts on demand you should use a simple loading tool like RequireJS.
Loading scripts on demand
Loading on demand can happen at any point in time, based on how the user is interacting with the application. it will be done the same way as loading scripts on the window.load event, using a script loader.
This method is very useful when certain functionality is not needed when you load the page, but only on certain cases. For example: only when a user focuses on the search input, we will load the autocomplete functionality.