Home > Enterprise >  When does onload fire for async script?
When does onload fire for async script?

Time:05-03

The following snippet is taken from an example in Google API doc. The intriguing part of this snippet is that onload event handler in the two <script async> in <head> are defined later in the <body>. Does the onload event in the async script only fire after the <body> are parsed? Does any spec provide such guarantee? Or this code is only correct under the implied assumption that these two particular scripts in <head> takes a long time to fetch and execute?

<!DOCTYPE html>
<html>
<head>
  <script async defer src="https://apis.google.com/js/api.js" onl oad="gapiLoad()"></script>
  <script async defer src="https://accounts.google.com/gsi/client" onl oad="gisInit()"></script>
</head>
<body>
  <script>

    function gapiLoad() {
       // do something 
    }

    function gisInit() {
       // do something 
    }

    // there are other stuffs...

  </script>
</body>
</html>

CodePudding user response:

No async alone doesn't ensure the script will be executed after the document has been parsed. It will load the script in parallel and execute it as soon as possible (so if the fetching of the script finishes before the parser reaches the <script> where a load event would be attached, that could create a problem indeed).

However here they do attach the load handler through the onload attribute, so they don't risk facing this problem, and they also added the defer attribute, which will force the script to wait after the document has been fully parsed before executing.

You can refer to these docs for more details.

CodePudding user response:

Onload EventHandler Supports these HTML tags: <body>, <frame> (deprecated), <iframe>, <img>, <input type="image">, <link>, <script>, <style>, <track>, <svg>, <use>, <foreignObject>, <image>, <object>, <embed. (Merci to @Kaiido for completing this list.)

If you want to be sure that your JS only runs when the DOM is loaded, you can load a handler function from the body tag.

Note You need to know when using onl oad with async that when scripts are loaded asynchronously, they delay the onl oad event. Often, asynchronously loaded scripts load other scripts.

function start() {
  gapiLoad();
  gisInit();
}

function gapiLoad() {
  console.log(1)
  // do something 
}

function gisInit() {
  console.log(2)
  // do something 
}
    
    // there are other stuffs...
<head>
<script async defer src="https://apis.google.com/js/api.js" ></script>
<script async defer src="https://accounts.google.com/gsi/client"></script>
</head>

<body onl oad="start()">

  • Related