700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 如何在页面加载完成后再去做某事?什么方法可以判断当前页面加载已完成?...

如何在页面加载完成后再去做某事?什么方法可以判断当前页面加载已完成?...

时间:2019-04-14 06:40:27

相关推荐

如何在页面加载完成后再去做某事?什么方法可以判断当前页面加载已完成?...

javascript提供了document.readyState=="complete"方法来解决当前页面加载判断的问题。<script type="text/javascript">function initView(){ if (document.readyState=="complete") { //此处可以填充具体的处理方法 alert("The page is already Load!"); } } </script> <html> <head></head> <body οnlοad="initView();"> <!--具体内容省略-----> </bodu> </html> ===================================================================================方法一:function waitThenDoIt(){try{if (window.document.readyState){//IEif (window.document.readyState==’complete’){doIt();}elsesetTimeout("waitThenDoIt()",10);} else {//Firefoxwindow.addEventListener("load",function(){doIt();},false);} } catch (ex) {}}function doIt(){//…}将代码中的:window.addEventListener("load",function(){doIt();},false);替换为:window.addEventListener("DOMContentLoaded",function(){doIt();},false);也可以。方法二:做页面时经常会遇到当前页面加载完成后,执行某些初始化工作。这时候就要知道如何判断页面(包括IFRAME)已经加载完成,代码如下:<script language="javascript">document.onreadystatechange = statechange;function statechange() {if(document.readystate == 'complete') {for(i=0; i<window.frames[].length; i++) {window.frames[i].document.onreadystatechange = statechange;if(window.frames[i].document.readystate != 'complete') {statechange();return;}}}}</script>此方法可以写在公用js中,其他方法调用判断即可方法三:window..onload的是页面加载完成后执行的事件,而且winodw.onload不能多次执行,jquery的$(fn)解决了这个问题,但是不使用jquery的情况下呢?以下是老外写的解决办法Js代码 复制代码addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) exec(); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。