when is the Javascript event loop triggered in a H

2019-08-20 07:44发布

I'am aware that the JS function (i.e. 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.

1条回答
beautiful°
2楼-- · 2019-08-20 08:03

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.

查看更多
登录 后发表回答