#Website performance

Placing JavaScript Tags in Your HTML: A Complete Guide

Sander van Surksum
by Sander van Surksum
Placing JavaScript Tags in Your HTML: A Guide

It's not an uncommon predicament - where and how to correctly position your <script> tags within your webpage. This might seem like a trivial consideration, but proper placement of these tags can significantly impact the performance and efficiency of your website.

Setting the Stage with <script> #

First and foremost, placing your <script> tags in the <head> of your HTML is a good rule of thumb. Think of this as setting the stage for a grand performance. Your HTML is the theatre; your <script> tags are the stagehands that ensure the show runs smoothly. By declaring your script at the head, you establish the tools your page will need to put on a stellar show for your visitors.

The Magic of 'Async' #

Once you've set your stage, it's time to start thinking about performance. Embrace the async attribute as your go-to approach for <script> tags. This attribute allows your script to load in the background, independently from the rest of the webpage. It's akin to having a stagehand working on setting up the props even while the act is going on – everything continues without a hitch!

Execution of Async Scripts #

Scripts with the async attribute can load concurrently with the parsing of the HTML document. However, as soon as an async script finishes loading, it forces the HTML parser to pause and allows the script to execute.

This execution order can lead to a somewhat haphazard timing, as scripts execute exactly when they finish loading, regardless of their position or order in the HTML document. It's comparable to an impromptu performance on stage, where the actors perform as soon as they're ready, without regard for the planned sequence of events.

While this can lead to speedier loading times, it may cause issues if your scripts depend on each other. For instance, if script B depends on script A, but script B loads faster and executes first, it may lead to errors.

The Timeliness of 'Defer' #

But what about scripts that rely on a fully constructed Document Object Model (DOM)? This is where the defer attribute comes into play. By deferring a script, you ensure it only runs once the HTML document has been completely loaded and parsed. This consideration is critical for efficient loading - timing is everything.

Execution of Defer Scripts #

Unlike async, scripts with the defer attribute maintain their order of execution based on their order in the HTML document. While they also load concurrently with the HTML parsing, defer scripts do not execute until after the HTML document has been fully parsed.

This is like a well-rehearsed play where all actors know their cues and perform in the correct sequence. Even if an actor (script) is ready early, they wait for their turn to perform, ensuring the storyline (script dependencies) makes sense to the audience (the webpage).

Defer is therefore a safer option when you have scripts that depend on each other, as it maintains the order of execution.

In conclusion, while both async and defer offer significant performance benefits over synchronous scripts, their use should be determined by your scripts' dependencies. For independent scripts, or those where execution order doesn't matter, async can help speed up loading times. For scripts with dependencies, defer ensures that everything runs in the right sequence. Understanding these nuances empowers you to design a webpage that delivers both superior performance and an optimal user experience.

Beware the Anti-pattern #

Avoiding the use of async and defer is equivalent to strolling headlong into anti-pattern territory. It's a pitfall we all want to sidestep. These attributes have been designed to optimise the loading and parsing of your scripts and thereby improve the overall user experience. Using them is embracing progress, not regression.

Rethinking the Footer #

A common but outdated practice is tucking away <script> tags in the footer. This method has fallen out of favour in recent years and is now considered an anti-pattern. We must always strive to stay ahead of the curve and adapt to modern best practices.

The Unwritten Rule: Avoid Synchronous Loading of Third-Party Scripts #

Finally, let's discuss an unwritten rule that is vital to the reliability of your website: Avoid synchronous loading of third-party scripts. The reason? If your website's uptime depends on the reliability of a third-party script, then you've essentially given control of your website's functionality to an external entity. Instead, opt to keep your website's uptime within your control, not subject to the whims of external factors.

In conclusion, thoughtfully positioning your <script> tags and employing async and defer effectively can lead to a significant boost in your website's performance. So the next time you're grappling with script tags, remember these tips, and set the stage for a top-tier performance!

Render and Parser Blocking #

When discussing script tag placement and website performance, we cannot overlook the impacts of synchronous scripts – those that lack async or defer attributes. Specifically, we must address the phenomenon of 'render blocking' and 'parser blocking', two serious issues that can impair your site's loading efficiency.

Render Blocking #

Scripts that are placed synchronously in the <head> of the HTML document are known as 'render-blocking'. In essence, when the browser encounters a <script> tag during the parsing of the HTML, it must stop and execute the script before it can continue.

This behaviour has a significant consequence: it halts the construction of the DOM and delays the render of the webpage. In layman's terms, it's like stopping the entire rehearsal on a theatre stage just because one actor forgot their lines. As you can imagine, this can cause noticeable delays in your webpage loading, leading to a less than optimal user experience.

Parser Blocking #

On the other hand, synchronous scripts placed in the <body> of the HTML are 'parser-blocking'. The mechanics of parser-blocking scripts are similar to render-blocking ones. The HTML parser must stop and execute the script before it can proceed.

However, parser blocking, while similar to render blocking, has a slightly different impact. Since the scripts are placed within the body, the initial page render isn't delayed. Instead, it halts the parser from constructing the rest of the DOM and delays the loading of subsequent resources.

It's akin to building a house where the construction team must halt work whenever a delivery arrives; they cannot proceed until the delivered goods are fully accounted for and stored. While the house's facade might be ready, the interior work stalls, delaying overall completion.

Striking a Balance #

Understanding the difference between render and parser blocking is crucial for optimising your webpage's performance. While synchronous scripts have their place, they need to be handled judiciously to prevent unnecessary delays.

As we've discussed, incorporating the use of async and defer attributes can make a significant difference. By allowing scripts to load in the background or after the HTML has parsed, these attributes ensure your webpage's 'show' goes on seamlessly, delivering a superior user experience.

Continue reading

Get more business out of your website

The performance of your website needs improvement.

You can get more business by creating happy customers by giving them a good user experience. Start now and request a performance audit.