简体   繁体   中英

When is the Javascript event loop triggered in a HTML page?

I'm aware that the JS function (ie setTimeout(function(){...}, TIME) ) places the function it received as a parameter in the Browser's event loop, and that this event loop will be processed after all inline/synchronous JS call are processed.

But what actually happens when he have the following HTML page structure:

<html>
 <head>
  <script> MANY INLINED SCRIPTS </script>
  <script src="file.js"></script>
  <script> setTimeout(function(){...}, TIME)</script>
   .
   .
   .

and the page goes, with probably this structure repeating itself until the </html> is reached.

When will the Event queue be processed in such situation?

edit: I want to create some sort of Lazy Loader for the scripts in my page. I rely in content coming from other sources that should appear only after the DOM is parsed and, hopefully, responsive.

Each inline script is processed as soon as the closing </script> tag is found. Similarly, the <script> tags that import scripts from the server as separate files are processed when the files are received, and that process is synchronous - the browser waits for the script contents before processing (except see the relatively new "async" attribute for <script> tags edit and the old "defer" attribute on IE, which may or may not have ever worked predictably (thanks @RobG)).

Thus your inline code with a call to setTimeout() will run when the browser sees the complete <script> block, and then the function passed will be invoked after the given number of milliseconds (roughly) has elapsed. You can't rely too heavily on accuracy of timeout handling.

There are other events besides the timeout mechanism: user interactions, ajax, etc. Those all get funneled through the same gateway, conceptually; that is, if your timeout is scheduled to run, but a user clicks a button a few milliseconds beforehand, your timer code will wait for the button processing to finish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM