一个浏览器渲染和操作的顺序如下:
1、HTML解析完毕;
2、外部脚本和样式表加载完成;
3、脚本爱文档内解析并执行;
4、HTML DOM完全构造起来;
5、图片和外部内容加载。
由此顺序下来,当dom加载完毕前就执行对应的dom操作势必会出问题,原来我们中文站的search suggest的错误就在于此。对于的一些方法:
第一种,最常见最简单的做法,等待页面完全加载完毕后触发。也就是绑定window对象的onload事件。:
window.onload=function(){
//相应操作;
}
第二种,因为在页面中途嵌入的含内脚本可以访问该位置之前的DOM,所以可以变通地在页面最底部添加脚本来执行。
第三中,写一个函数自己判断Dom的加载
function domReady( f ) {
// If the DOM is already loaded, execute the function right away
if ( domReady.done ) return f();
// If we’ve already added a function
if ( domReady.timer ) {
// Add it to the list of functions to execute
domReady.ready.push( f );
} else {
// Attach an event for when the page finishes loading,
// just in case it finishes first. Uses addEvent.
addEvent( window, “load”, isDOMReady );
// Initialize the array of functions to execute
domReady.ready = [ f ];
// Check to see if the DOM is ready as quickly as possible
domReady.timer = setInterval( isDOMReady, 13 );
}
}
// Checks to see if the DOM is ready for navigation
function isDOMReady() {
// If we already figured out that the page is ready, ignore
if ( domReady.done ) return false;
// Check to see if a number of functions and elements are
// able to be accessed
if ( document && document.getElementsByTagName &&
document.getElementById && document.body ) {
// If they’re ready, we can stop checking
clearInterval( domReady.timer );
domReady.timer = null;
// Execute all the functions that were waiting
for ( var i = 0; i < domReady.ready.length; i++ )
domReady.ready[i]();
// Remember that we’re now done
domReady.ready = null;
domReady.done = true;
}
}
ps:很佩服老外,会为了这么点速度上的先后去写专门的函数。想想国内会有多少公司去这么做
