Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

4 Places to Load JavaScript

, 5 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

  1. In <head>
  2. Before </body>
  3. After page load
  4. 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.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nathan Gloyn
Nock Consulting
United Kingdom United Kingdom
Passionate developer, designer, Certified Scrum Professional, wanna-be architect, agile evangelist, and presenter.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150302.1 | Last Updated 5 Mar 2014
Article Copyright 2014 by Nathan Gloyn
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid