如何在页面加载完成后再去做某事?什么方法可以判断当前页面加载已完成?
2016-07-25 18:40
549 查看
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 onload="initView();"> <!--具体内容省略-----> </bodu> </html> =================================================================================== 方法一: function waitThenDoIt(){ try{ if (window.document.readyState){//IE if (window.document.readyState==’complete’){ doIt(); }else setTimeout("waitThenDoIt()",10); } else {//Firefox window.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); } })();
相关文章推荐
- 进制转换-java语言
- 2个YUV视频 拼接技术
- 机器学习算法比较
- hdu 4435 charge-station【暴力+Bfs】
- Python下redis setex函数的两种参数顺序
- Spring的作用域以及RequestContextListener作用
- hdu4897(树链剖分)
- [置顶] C语言做的接鸡蛋小游戏(附源码注释)【原创】
- 初学Struts2第一天,学习Struts基础配置,第一次写博文,写的不好勿喷哦
- 使用腾讯TAB做成的第一个demo
- poj3150 Cellular Automaton(矩阵快速幂)
- 指针数组
- 专访程炳皓:八年一觉“开心”梦
- jdk1.7--ArrayList
- DataSetToJSON
- activity中oncreate的参数的意义
- UVA 796 Critical Links (桥)
- Mongodb 3节点 Rep set +sharding 配置
- [转] ImageView的android:adjustViewBounds属性
- CodeForces 288C