After doing so, we quickly realized that following the guidelines indicated on RequireJS.org would have the opposite effect on our dashboard and make us lose the benefit of the biggest browser performance improvement ever: the look-ahead pre-parser.
On the RequireJS website you can find a snippet that shows how to include the library in the html head:
<script data-main="js/main" src="js/require.js"></script>
What’s happening here? The
require.js script loads first, synchronously, then once parsed and executed, it programmatically requests the file referenced in the
js/main.js (the file that contains your code).
Since the second file loads asynchronously, (i.e. in the background) it doesn’t block the page rendering. This is why RequireJS can claim to speed up (most) websites.
When using the data-main attribute, files are loaded in sequentially.
When using a regular script tag, files are loaded in parallel.
You lose the benefit of the biggest browser performance improvement ever!
The preloader will detect all resources (js, css, images…) in the document and retrieve them in the background.
Unsurprisingly, browsers implement that feature differently. For example, Chrome re-prioritizes resources and loads the ones it considers critical first. Consequently, js files inserted at the very bottom of the document will be downloaded before other resources, even inline images inserted up front.
As a result, without you having to intervene, your website gets instantly faster. A study proved it can deliver a ~20% speed improvement.
This is why it may be a better option to include js/main.js as a script tag.
Using RequireJS to circumvent the pre-loader
Actually, there is a case where you may not want to use a script tag and RequireJS’s
data-main attribute may come in handy: if you want to circumvent the pre-loader behaviour.
Let’s say you have an e-commerce website that heavily relies on images and your user base is predominantly using Chrome. As mentioned before, Chrome will prioritize scripts over inline images. If you want to ensure your images get loaded first, using RequireJS programmatic loading would be the way to go.
RequireJS is a must-have in your toolbox, a real game-changer. At HootSuite we use it and we love it!
Thanks to Jeff Stautz, Gabriel Gosselin and Steve Mynett for their reviews!