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

两盒软妹~` 提交于 2019-12-25 03:25:47

问题


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:


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.



来源:https://stackoverflow.com/questions/12729438/when-is-the-javascript-event-loop-triggered-in-a-html-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!