Using defer in script tags

The process which browser follows when it encounters a script tag in html page is as following:

Stop the HTML parser -> Download the script -> Parse the script -> Execute the script

This way, as soon as browser finds a script tag, it stops the current parsing of HTML and first downloads, then parses and then immediately executes the script.

Because of such a behavior, HTML parsing gets delayed and rendering of a page can take longer. This increase in load time of page can definitely prove to be a turn off for users.

One way to ensure that browser doesn’t invest time in executing the script is to add ‘defer’ attribute to script tag. When defer attribute is added to script tag, then browser starts executing all such scripts only when the HTML parsing is completed. This way, script execution doesn’t hinder the page rendering or loading.

Note that defer attribute is not to be used with values as true or false, rather it just needs to be mentioned in the script tag as following:

<script src=”path of file” type=”text/javascript” defer></script>

Also, remember that defer can be used only with those script tags which also have src attribute. For all the script tags with code embedded within HTML page, all such code is executed instantly by the browser and not after HTML parsing.

So, use defer and improve your page load time!


One thought on “Using defer in script tags

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s