如何在没有框架的情况下检查DOM是否准备就绪? [英] How to check if DOM is ready without a framework?
问题描述
- 不使用像jQuery等框架;
- 不知道你是否脚本已经通过静态放置的
< script>
标签或通过其他JavaScript稍后加载,DOM已经加载。
可以这样做或多或少可靠地进行,并且具有跨浏览器兼容性?
已添加: strong>让我澄清一点:我正在编写一个独立的.JS文件,可以包含在任意的网页中。我想执行代码 AFTER DOM加载。但我不知道如何我的脚本将被包含。可以通过放置< script>
标签(在这种情况下,传统的 onload
或DOM-准备解决方案将工作);或者它可以通过AJAX或其他方式加载,很久以后DOM已经加载(所以前面提到的解决方案永远不会启动)。
document.readyState
属性可用于检查文档是否准备好:
if(document.readyState ===complete){
//已经加载!
}
else {
//在此添加onload或DOMContentLoaded事件侦听器:例如
window.addEventListener(onload,function(){/ *您的代码在这里* /},false);
//或
//document.addEventListener(\"DOMContentLoaded,function(){/ * code * /},false);
}
The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here's the catch:
- Without using a framework like jQuery etc;
- Without knowing if your script has been loaded via a statically placed
<script>
tag or via some other Javascript much later after the DOM has already loaded.
Can this be done more or less reliably and with cross-browser compatibility?
Added: Let me clarify: I'm writing a standalone .JS file which can be included in arbitrary webpages. I want to execute code AFTER the DOM has been loaded. But I don't know HOW my script will be included. It could be by placing a <script>
tag (in which case the traditional onload
or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire).
The document.readyState
property can be used to check if the document is ready:
if(document.readyState === "complete") {
//Already loaded!
}
else {
//Add onload or DOMContentLoaded event listeners here: for example,
window.addEventListener("onload", function () {/* your code here */}, false);
//or
//document.addEventListener("DOMContentLoaded", function () {/* code */}, false);
}
这篇关于如何在没有框架的情况下检查DOM是否准备就绪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!