[英]Event listener on DOMContentLoaded fires randomly
I have a script on a page which is working most of the time but not always, and I'd like to know why. 我在页面上有一个脚本,大部分时间都在工作,但并不总是如此,我想知道原因。
This script is imported via: 此脚本通过以下方式导入:
<script src="script.js" async></script>` tag in `<head>
And the content of the script is: 脚本的内容是:
console.log("loading"); // always gets printed
document.addEventListener("DOMContentLoaded", function() {
console.log("outer"); // sometimes get not printed
(function() {
console.log("inner"); // sometimes get not printed
})();
});
The browser console always outputs loading
but sometimes it doesn't output the rest (both outer
and inner
). 浏览器控制台总是输出
loading
但有时它不输出其余的( outer
和inner
)。 Doing either a hard refresh on the page or simply reloading it (hitting Enter
on the address bar) doesn't seem to influence this behavior (same results each way). 在页面上进行硬刷新或者只是重新加载它(在地址栏上按
Enter
)似乎不会影响这种行为(每种方式都有相同的结果)。
I'll also add that outer
and inner
are always printed by pair, there is never one without the other. 我还要补充说,
outer
和inner
总是按对打印,没有一个没有另一个。
Is there a problem in the way I'm listening to DOMContentLoaded
? 我正在听
DOMContentLoaded
的方式有问题吗? Or would I have to load the script outside <head>
(which I would prefer not to, if possible)? 或者我是否必须在
<head>
之外加载脚本(如果可能的话我不想这样做)?
async
script tags are executed as soon as the code has been loaded, regardless of whether the DOM content has been loaded or not. 无论是否已加载DOM内容,都会在加载代码后立即执行
async
脚本标记。 So in general, do not use this for DOM-relevant operations. 所以一般来说,不要将它用于与DOM相关的操作。
Instead, if you want your file to load but your code to execute only after DOMContentLoaded
, use the defer
attribute. 相反,如果您希望加载文件但是您的代码仅在
DOMContentLoaded
之后执行,请使用defer
属性。 You wont need an event listener in your code in this case: 在这种情况下,您不需要代码中的事件侦听器:
Image Source: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
图片来源: http : //peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
A word of caution though, defer
is buggy in IE9 and below. 但需要注意的是,
defer
在IE9及以下版本中出现错误。
您的脚本在触发DOMContentLoaded事件后执行,因此设置侦听器为时已晚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.