New Method Of Adding External Javascript File

New Method Of Adding External Javascript File

An old-school approach to this issue was to add your script element at the bottom of the body (e.g., just before the tag), so that it would load after all the HTML has parsed. The downside with this approach is that the script cannot be loaded or parsed until the HTML DOM has been loaded. This can pose a significant performance issue on big sites with a lot of JavaScript, slowing down your site.

newbody.png

We can actually apply two new methods to get around the blocking script problem:

1.async

2. defer .

Let's have a look at how these two vary.

async

Scripts loaded with the async attribute will download without pausing the page while they are being downloaded. The script, however, will run once the download is complete, preventing the page from rendering. There is no guarantee that scripts will run in the sequence you specify. When the scripts on the page operate independently of one another and don't rely on any other script on the page, async is the ideal option.

bodyasync.png

defer

The defer attribute allows scripts to load in the order they appear on the page. They won't run until the entire page content has loaded, which is important if your scripts rely on the DOM (e.g. they modify one or more elements on the page).

bodydefer.png

conclusion

Both async and defer direct the browser to download the script(s) in a different thread while the rest of the page (DOM, etc.) is loading, so the page doesn't get trapped in the fetching process.

Scripts using the async feature run as soon as the download is complete. This prevents the page from being loaded and does not ensure a precise execution sequence.

Scripts using the defer feature will load in the order they are specified, and will not run until all of the other scripts have completed loading.

Use async if your scripts need to run right away and don't have any dependencies.

If your scripts require to wait for parsing and/or the DOM to be ready, load them using defer and place their associated script tag elements in the order you want the browser to execute them.

if you like my article you can support me here