- In <head>
- Before </body>
- After page load
- On demand
He then went on to offer some guidance on common things you’d load in each place:
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.
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
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).
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.