我正在执行一个外部脚本,使用<脚本>内<头>。

现在,由于脚本在页面加载之前执行,我不能访问<body>等。我想在文档被“加载”(HTML完全下载并在ram中)后执行一些JavaScript。是否有任何事件,我可以挂钩到当我的脚本执行,这将在页面加载触发?


当前回答

Working Fiddle on <body onload="myFunction()" >

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript">
   function myFunction(){
    alert("Page is loaded");
   }
  </script>
 </head>

 <body onload="myFunction()">
  <h1>Hello World!</h1>
 </body>    
</html>

其他回答

如果你正在使用jQuery,

$(函数 () {...});

等于

美元(文档)。Ready (function () {})

或者另一个简写:

(美元)。Ready (function () {})

查看什么事件JQuery $function()火?和https://api.jquery.com/ready/

看钩文件。jQuery $(document).load(…)

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 = ...
document.onreadystatechange = function(){
     if(document.readyState === 'complete'){
         /*code here*/
     }
}

看这里:http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx

Working Fiddle on <body onload="myFunction()" >

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript">
   function myFunction(){
    alert("Page is loaded");
   }
  </script>
 </head>

 <body onload="myFunction()">
  <h1>Hello World!</h1>
 </body>    
</html>