Wednesday 5 March 2014

4 Places to load JavaScript

I watched Enough with the JavaScript Already by Nicholas Zakas the other day and one thing that stuck with me was him outlining 4 places within your page to load JavaScript

  • In <head>
  • Before </body>
  • After page load
  • On demand

Nicholas points out that you don’t just have to load JavaScript in one place, you need to think about what your users will do on the page and this should guide where you load your script.

He then went on to offer some guidance on common things you’d load in each place:

In <head>
To determine how your users are using the site you need analytics, often those scripts state they have to be in the head e.g. Google Analytics. If you are going to put something here it should be absolutely minimal such as boot strap code. 

Before </body>
You should add scripts here that control functionality that users do immediately the page is loaded.

After page load
Once your page is loaded then load scripts that control functionality that the user may do shortly after the page is loaded scripts needed soon after page load

On demand
This is loading a script when needed specifically relating to what the user is doing. The functionality this relates to is code that is used infrequently by the majority of the users of your site (<25%).  Nicholas mentioned a blog post by Alex Sexton which talks about doing this amongst other things (also a good read).

Summary

What I specifically took away from this part of his presentation was that all too often before </body> becomes a dumping ground with scripts being put there with no real thought as to what is actually needed on the page.

Something else that crossed my mind is if you’re building a SPA you may think you’re already doing this using require.js or similar mechanism, loading only scripts as you need them, but it may pay you to take a closer look and work out exactly what is loaded and when, perhaps its not being as efficient as you think.