问题:
异步加载js文件,然后在执行加载文件的回调之前检查是否加载了dom.
编辑:我们不使用jQuery; 我们使用Prototype.
编辑:为代码示例添加了更多注释.
大家好,
我正在尝试异步加载我的所有js文件,以防止它们阻塞页面的其余部分.但是当脚本加载并调用回调时,我需要知道DOM是否已经加载,所以我知道如何构造回调.见下文:
//load asynchronously
(function(){
var e = document.createElement('script');
e.type = "text/javascript";
e.async = true;
e.src = srcstr;
// a little magic to make the callback happen
if(navigator.userAgent.indexOf("Opera")){
e.text = "initPage();";
}else if(navigator.userAgent.indexOf("MSIE")){
e.onreadystatechange = initPage;
}else{
e.innerHTML = "initPage();";
}
// attach the file to the document
document.getElementsByTagName('head')[0].appendChild(e);
})();
initPageHelper = function(){
//requires DOM be loaded
}
initPage = function(){
if(domLoaded){ // if dom is already loaded, just call the function
initPageHelper(); …Run Code Online (Sandbox Code Playgroud) 我想在所有异步文件加载后"引导"我的页面.有没有办法在加载异步文件时收到通知?
的index.html
<script src="fileone.js" type="text/javascript" async></script>
<script src="filetwo.js" type="text/javascript" async></script>
<script src="bootstrap.js" type="text/javascript" async></script>
Run Code Online (Sandbox Code Playgroud)