首页 > 代码库 > Window.onload与$(document).ready()的对比

Window.onload与$(document).ready()的对比

window.onload:必须等待网页中所有内容加载完毕才执行(包括图片)

例如:

   1:  window.onload=function(){
   2:      alert("test1");
   3:  };
   4:   
   5:  window.onload=function(){
   6:      alert("test2");
   7:  };
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

其结果只会显示test2

而$(document).ready():网页中所有的dom结构绘制完毕就执行,可能dom元素关联的东西还没有加载完.例如:

   1:  $(document).ready(function(){
   2:      alert("Hello,World!");
   3:  });
   4:  $(document).ready(function(){
   5:      alert("Hello again.");
   6:  });
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>会依次弹出”Hello,World!”和”Hello,again.”Smile