Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

One major cause of slow web pages is the so-called blocking script. A blocking script is a JavaScript file whose loading and execution blocks the loading of a web page. In extreme circumstances, a browser may download an entire webpage and show a blank screen for several seconds or longer while the JavaScript is loaded and parsed. Because web users tend to become bored quickly, this situation should absolutely be avoided.

Fortunately, there are several ways to defer JavaScript loading and execution and to make your web pages display faster.

The first way is by using the defer attribute of the script element. Here’s what it looks like:

Note that the defer attribute can be used only with external JavaScript files. It can’t be applied to

Another attribute for helping to defer JavaScript is the async attribute. The async attribute is new in HTML5. Here’s what it looks like:

Like the defer attribute, the async attribute can only be used with external scripts (where the src attribute is used). When present, the async attribute will cause the script to be executed asynchronously with the rest of the page. In other words, the script will execute at the same time as the rest of the page.

Whichever method you choose to use may have an effect on whether the rest of the JavaScript on your page runs correctly. Make sure to test everything after implementing deferred loading. Done correctly, deferring JavaScript can dramatically decrease your users’ wait time and make everyone happier.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: