[英]$(window).on(“load”,fn) not working
I'm using jQuery to check if the website resources are loaded properly. 我正在使用jQuery检查网站资源是否正确加载。 To test if it works I put into the index.html a wrong CSS file. 为了测试它是否有效,我在index.html中放入了错误的CSS文件。
If I put the following code in the Javascript file , that is included in the head, the message "CSS missing" doesn't appear. 如果将以下代码放入包含在头部的Javascript文件中 ,则不会出现“缺少CSS”消息。
$(window).on("load",function () {
console.log("loaded")
$("link").on("error",function(){
console.log("CSS missing");
});
});
Instead, if I put the following code at the end of the body in the index.html, the message loading error is printed 相反,如果我将以下代码放在主体的末尾的index.html中,则会显示消息加载错误
<script>
$("link").on("error",function(){
console.log("loading error");
});
</script>
I need the Javascript file working, what I'm doing wrong? 我需要Javascript文件工作,我在做什么错?
NOTE : Using $(document).ready(fn) also not work. 注意 :使用$(document).ready(fn)也不起作用。
I can't include the javascript at the end of the body because the same script also monitors the page loading time. 我不能在主体末尾添加javascript,因为同一脚本还会监视页面加载时间。 I need something that is executed at the end of the body with the javascript included in the head. 我需要在主体结尾处执行的操作,其中包含头部中的javascript。
SOLUTION without jQuery: I used document.addEventListener('DOMContentLoaded', fn())
instead of $(document).ready(fn)
and now all it's working properly. 没有jQuery的解决方案 :我使用document.addEventListener('DOMContentLoaded', fn())
而不是$(document).ready(fn)
,现在一切正常。 Why? 为什么? I don't know. 我不知道。
Loading error appears because the code is executed during the parsing of file, but the file might not be downloaded yet. 由于在解析文件期间执行了代码,因此出现加载错误,但文件可能尚未下载。 Try using instead: 尝试改用:
$(document).ready(function(){
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.