何时在HTML页面中触发Javascript事件循环? [英] when is the Javascript event loop triggered in a HTML page?

查看:155
本文介绍了何时在HTML页面中触发Javascript事件循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JS函数(即setTimeout(function(){...},TIME))将它作为参数接收到的函数放入浏览器的事件循环中,并且此事件循环将在所有内联/同步JS调用都被处理。



但是当他有以下HTML页面结构时会发生什么:

 < HTML> 
< head>
< script>许多倾斜的脚本< / script>
< script src =file.js>< / script>
< script> setTimeout(function(){...},TIME)< / script>



,并且页面可能会重复,直到<



何时会在这种情况下处理事件队列?

编辑:我想为我的页面中的脚本创建某种Lazy Loader。我依赖来自其他来源的内容,这些内容应该在DOM解析出来之后才会出现,并且希望能够作出响应。

解决方案

每个内联只要发现结束< / script> 标记,就会处理脚本。类似地,接收文件时处理从服务器导入脚本作为单独文件的< script> 标记,并且该过程是同步的 - 浏览器等待脚本处理前的内容(除了在IE上查看< script> tags edit 和旧的defer属性的相对较新的异步 ($ @
$ b

因此,您调用 setTimeout()的内联代码可以预测(也可能没有预见到)(感谢@RobG) code>将在浏览器看到完整的< script> 块时运行,然后传递的函数将在给定的毫秒数(大致)过去。你不能过分依赖超时处理的准确性。



除超时机制外还有其他事件:用户交互,ajax等等。概念上相同的网关;也就是说,如果您的超时计划运行,但用户预先点击了几毫秒的按钮,您的计时器代码将等待按钮处理完成。


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.

解决方案

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.

这篇关于何时在HTML页面中触发Javascript事件循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆