Synchronous and Asynchronous Script Loading
By Stephen Bucaro
When a web page is loaded, the browser parses through the code identifying each html tag
and performing whatever rendering or loading function that tag defines. By default that
action occurs synchronously. In other words the browser downloads and executes any scripts
that it encounters during the parsing of the web page. If the script is external, that is,
it has a src attribute, the browser will send a request for the resource and pause
further parsing until the file has completed downloading and executing.
In the synchronous loading example shown above, scriptTwo.js is loaded only when the loading
of and executing of scriptOne.js is complete.
Asynchronous script loading causes the external scripts to be loaded asynchronously, in other
words along side other downloading and rendering of the webpage.
<script async src="scriptOne.js"></script>
<script async src="scriptTwo.js"></script>
Note the keyword async in the script links shown above. This causes both scripts to
be loaded concurrently, alongside other scripts getting loaded synchronously, and alongside
the rendering of the webpage.
In theory this causes the webpage to render more quickly so the user is not forced to wait
until the script loading is complete and allows the user to communicate with web page as
the script is downloaded in the background.
Google Developers Website says to use asynchronous script loading so that the webpage can
render more quickly. However, this can cause dangerous consequences. First, if a webpage element
is rendered and the user attempts to interact with it before its related script has completed
downloading, this could cause an error. Second, if a script itself has any effect on the appearance
of the webpage, the webpage will blink when switching from the originally rendered webpage to the
final rendered webpage after the script completes loading and executing. This is referred to as
FOOC (Flash Of Original Content).
<script src="demo_defer.js" defer ></script>
One common problem is that a function triggered by an html element, like a form, cannot
execute if that element has not yet completed rendering. In that case you might want to use the
defer attribute. When present the defer attribute specifies that the script is
to be executed only when the page has finished rendering.
The fact is, whether to use synchronous or asynchronous script loading depends upon the
design of the webpage. Asynchronous script loading can cause the webpage can render more quickly.
But if done without consideration for the design it can cause webpage flash or even errors.
More Java Script Code:
• Java Script Trim Function
• Easy Picture Panning Code
• Easy Java Script Animation
• Sams Teach Yourself HTML5 in 10 Minutes
• Java Script Code to Factor Numbers
• Calculators For Your Web Site
• How to Disable the Browser Back Button
• Easy Java Script Windows