Chapter 4. Loading Scripts Without Blocking
SCRIPT tags have a negative
impact on page performance because of their blocking behavior.
While scripts are being downloaded and executed, most browsers won’t
download anything else. There are times when it’s necessary to have this
blocking, but it’s important to identify situations when JavaScript can be
loaded independent of the rest of the page.
When these opportunities arise, we want to load the JavaScript in such a way that it does not block other downloads. Luckily, there are several techniques for doing this that make pages load faster. This chapter explains these techniques, compares how they affect the browser and performance, and describes the circumstances that make one approach preferred over another.
Scripts Block
JavaScript is included in a web page as an inline script or an external script. An
inline script includes all the JavaScript in the HTML document itself using the SCRIPT tag:
<script>
function displayMessage(msg) {
alert(msg);
}
</script>External scripts pull in the JavaScript from a separate file using
the SCRIPT SRC
attribute:
<script src='A.js'></script>
The SRC attribute specifies the
URL of the external file that needs to be loaded. The browser reads the
script file from the cache, if available, or makes an HTTP request to
fetch the script.
Normally, most browsers download components in parallel, but that’s not the case for external scripts. When the browser starts downloading an external script, it won’t start any ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access