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

javascript提供了document.readyState=="complete"方法来解决当前页面加载判断的问题。


 

   function initView(){ 


      if (document.readyState=="complete") 

   { 

      //此处可以填充具体的处理方法 

      alert("The page is already Load!"); 

   } 

   } 









===================================================================================

方法一:



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)已经加载完成,代码如下:


      document.onreadystatechange = statechange;

      function statechange() {

        if(document.readystate == 'complete') {

           for(i=0; i[].length;>

              window.frames[i].document.onreadystatechange = statechange;

              if(window.frames[i].document.readystate != 'complete') {

                 statechange();

                 return;

              }

            }

         }

      }



此方法可以写在公用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);  

        }  

    })(); 



document.readyState:判断文档是否加载完成。firefox不支持。


这个属性是只读的,传回值有以下的可能:

0-UNINITIALIZED:XML 对象被产生,但没有任何文件被加载。

1-LOADING:加载程序进行中,但文件尚未开始解析。

2-LOADED:部分的文件已经加载且进行解析,但对象模型尚未生效。

3-INTERACTIVE:仅对已加载的部分文件有效,在此情况下,对象模型是有效但只读的。

4-COMPLETED:文件已完全加载,代表加载成功。

document.onreadystatechange = subSomething;//当页面加载状态改变的时候执行这个方法.

function subSomething()

{

if(document.readyState == "complete"){ //当页面加载状态为完全结束时进入

//你要做的操作。

else if(document.readyState=="loading"){

}

}

比较好的例子:http://www.jb51.net/article/20445.htm

说明 :onreadystatechange 事件能辨识readyState 属性的改变。


document.all(只被IE支持)

action:document.layers是Netscape 4.x专有的属性,是一个代表所有由储如<div><layer>等定位了的元素的数组通常也是用<div> 或<layer>对象的id属性来引用的,但是这里面不包含除此以外的其它元素

document.layers和document.all的用法是一样的,功能也是相同的。所在我就只介绍一种用法:

document.all的意思是文档的所有元素,也就是说它包含了当前网页的所有元素。它是以数组的形式保存元素的属性的,所以我们可以用 document.all["元素名"].属性名="属性值"来动态改变元素的属性。用这条语句,可以做出许许多多动态网页效果,如:动态变换图片、动态 改变文本的背景、动态改变网页的背景、动态改变图片的大小、动态改变文字的大小各颜色等等。你简直可以动态控制所有网页元素。 

document.all[]这个数组可以访问文档中所有元素。


例1(这个可以让你理解文档中哪些是对象)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 

<head>

<title>Document.All Example</title>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />

</head>

<body>

<h1>Example Heading</h1>

<hr />

<p>This is a <em>paragraph</em>. It is only a <em>paragraph.</em></p>

<p>Yet another <em>paragraph.</em></p>

<p>This final <em>paragraph</em> has <em id="special">special emphasis.</em></p>

<hr />

<script type="text/javascript">

<!--

var i,origLength;

origLength = document.all.length;

document.write('document.all.length='+origLength+"<br />");

for (i = 0; i < origLength; i++)

{

document.write("document.all["+i+"]="+document.all[i].tagName+"<br />");

}

//-->

</script>

</body>

</html>

 它的执行结果是:

Example Heading


--------------------------------------------------------------------------------


This is a paragraph. It is only a paragraph.

Yet another paragraph.

This final paragraph has special emphasis.


--------------------------------------------------------------------------------


document.all.length=18

document.all[0]=!

document.all[1]=HTML

document.all[2]=HEAD

document.all[3]=TITLE

document.all[4]=META

document.all[5]=BODY

document.all[6]=H1

document.all[7]=HR

document.all[8]=P

document.all[9]=EM

document.all[10]=EM

document.all[11]=P

document.all[12]=EM

document.all[13]=P

document.all[14]=EM

document.all[15]=EM

document.all[16]=HR

document.all[17]=SCRIPT

(注意它只可以在IE上运行)  




<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>单击DIV变色</title>

<style type="text/css">

<!--

#docid{

height:400px;

width:400px;

}

-->

</style>

</head>

<body><div id="docid" name="docname" onClick="bgcolor()"></div>

</body>

</html>

<script language="javascript" type="text/javascript">

<!--

function bgcolor(){

document.all[7].style.backgroundColor="#000"

}

-->

</script>

上面的这个例子让你了解怎么访问文档中的一个特定元素,比如文档中有一个DIV

<div id="docid" name="docname"></div>,你可以通过这个DIV的ID,NAME 或INDEX属性访问这个DIV: 

document.all["docid"]

document.all["docname"]

document.all.item("docid")

document.all.item("docname")

document.all[7]

document.all.tags("div")则返回文档中所有DIV数组,本例中只有一个DIV,所以用 document.all.tags("div")[0]就可以访问了。

  3、使用document.all[]

例3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 

<head>

<title>Document.All Example #2</title>

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />

</head>

<body>

<!-- Works in Internet Explorer and compatible -->

<h1 id="heading1" align="center" style="font-size: larger;">DHTML Fun!!!</h1>

<form name="testform" id="testform" action="#" method="get">

<br /><br />

<input type="button" value="Align Left" 

onclick="document.all['heading1'].align='left';" />//改变<h1& gt;</h1>标签对中的align属性的值,下面的代码作用相同

<input type="button" value="Align Center"

onclick="document.all['heading1'].align='center';" />

<input type="button" value="Align Right"

onclick="document.all['heading1'].align='right';" />

<br /><br />

<input type="button" value="Bigger"

onclick="document.all['heading1'].style.fontSize='xx-large';" />

<input type="button" value="Smaller"

onclick="document.all['heading1'].style.fontSize='xx-small';" />

<br /><br />

<input type="button" value="Red"

onclick="document.all['heading1'].style.color='red';" />

<input type="button" value="Blue"

onclick="document.all['heading1'].style.color='blue';" />

<input type="button" value="Black"

onclick="document.all['heading1'].style.color='black';" />

<br /><br />

<input type="text" name="userText" id="userText" size="30" />

<input type="button" value="Change Text"

onclick="document.all['heading1'].innerText=document.testform.userText.value;" /& gt;//改变<h1></h1>标签对中的文本内容

</form>

</body>

</html>