wwaawaw
wwaawaw

Reputation: 7137

Will @async scripts ever run before their tags are encountered by the parser?

Here's what I mean. Take the following example:

<!doctype html>
<html>
  <head><title>test page</title></head>
  <body>
     Will this always be the first thing on the screen every time?
     <script>document.write('Will this be 2nd?');</script>
     <script async src="http://foo.bar/baz.js"></script>
  </body>
</html>

...where baz.js consists of the following:

var s = document.createElement('span');
s.innerHTML = 'Is there any possibility that this will be the first thing to appear on the screen whatsoever, like it\'s being loaded over a really badass fiber optic connection?';
document.body.appendChild(s);

I ask because my script depends on a body element already existing on the page for me to append to, but I'm not controlling where on the page my markup gets inserted other than the fact that I know it will be somewhere in the body. Are there browsers that do a scan over the markup for async and defer scripts before they begin their main round of parsing to see if there's anything they should start downloading beforehand?

Let me know if the question isn't clear enough and I'll try to clarify.

Thanks

Upvotes: 1

Views: 63

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075079

The script elements are not acted upon until the parser reaches them.

Your "Will this be 2nd?" script will always run before the other one.

In both cases, you can rely on document.body.

More reading on the full details of async and defer.

Upvotes: 1

Related Questions