我正在执行一个外部脚本,使用<脚本>内<头>。
现在,由于脚本在页面加载之前执行,我不能访问<body>等。我想在文档被“加载”(HTML完全下载并在ram中)后执行一些JavaScript。是否有任何事件,我可以挂钩到当我的脚本执行,这将在页面加载触发?
我正在执行一个外部脚本,使用<脚本>内<头>。
现在,由于脚本在页面加载之前执行,我不能访问<body>等。我想在文档被“加载”(HTML完全下载并在ram中)后执行一些JavaScript。是否有任何事件,我可以挂钩到当我的脚本执行,这将在页面加载触发?
当前回答
如果你正在使用jQuery,
$(函数 () {...});
等于
美元(文档)。Ready (function () {})
或者另一个简写:
(美元)。Ready (function () {})
查看什么事件JQuery $function()火?和https://api.jquery.com/ready/
其他回答
JavaScript
document.addEventListener('readystatechange', event => {
// When HTML/DOM elements are ready:
if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded"..
alert("hi 1");
}
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
alert("hi 2");
}
});
jQuery也一样:
$(document).ready(function() { //same as: $(function() {
alert("hi 1");
});
$(window).load(function() {
alert("hi 2");
});
注意:不要使用下面的标记(因为它会覆盖其他同类声明):
document.onreadystatechange = ...
看钩文件。jQuery $(document).load(…)
有一个关于如何使用Javascript或Jquery检测文档是否已加载的非常好的文档。
使用本地Javascript可以实现这一点
if (document.readyState === "complete") {
init();
}
这也可以在区间内完成
var interval = setInterval(function() {
if(document.readyState === 'complete') {
clearInterval(interval);
init();
}
}, 100);
由Mozilla编写
switch (document.readyState) {
case "loading":
// The document is still loading.
break;
case "interactive":
// The document has finished loading. We can now access the DOM elements.
var span = document.createElement("span");
span.textContent = "A <span> element.";
document.body.appendChild(span);
break;
case "complete":
// The page is fully loaded.
console.log("Page is loaded completely");
break;
}
使用Jquery 仅检查DOM是否准备就绪
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
要检查是否加载了所有资源,请使用window.load
$( window ).load(function() {
console.log( "window loaded" );
});
比较
在下面的片段中,我收集选择的方法并显示它们的序列。讲话
the document.onload (X) is not supported by any modern browser (event is never fired) if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one) event handler given in <body onload="..."> (F) is wrapped by additional onload function document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers. all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it). solutions readystatechange (C,D) are executed multiple times by browser but for different document states: loading - the document is loading (no fired in snippet) interactive - the document is parsed, fired before DOMContentLoaded complete - the document and resources are loaded, fired before body/window onload
<html> <head> <script> // solution A console.log(`[timestamp: ${Date.now()}] A: Head script`); // solution B document.addEventListener("DOMContentLoaded", () => { print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`); }); // solution C document.addEventListener('readystatechange', () => { print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`); }); // solution D document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)}; // solution E (never executed) window.onload = () => { print(`E: <body onload="..."> override this handler`); }; // solution F function bodyOnLoad() { print(`[timestamp: ${Date.now()}] F: <body onload='...'>`); infoAboutOnLoad(); // additional info } // solution X document.onload = () => {print(`document.onload is never fired`)}; // HELPERS function print(txt) { console.log(txt); if(mydiv) mydiv.innerHTML += txt.replace('<','<').replace('>','>') + '<br>'; } function infoAboutOnLoad() { console.log("window.onload (after override):", (''+document.body.onload).replace(/\s+/g,' ')); console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`); } console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' ')); </script> </head> <body onload="bodyOnLoad()"> <div id="mydiv"></div> <!-- this script must te at the bottom of <body> --> <script> // solution G print(`[timestamp: ${Date.now()}] G: <body> bottom script`); </script> </body> </html>
使用YUI库(我喜欢它):
YAHOO.util.Event.onDOMReady(function(){
//your code
});
便携又漂亮!然而,如果你不把YUI用于其他东西(参见它的文档),我会说它不值得使用。
注意:要使用此代码,您需要导入2个脚本
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>