对于上面的代码来说,当readystatechange事件触发时,会检测document.readyState的值,看当前是否已经进入交互阶段或完成阶段。如果是,则移除相应的事件处理程序以免在其他阶段再执行
另外,IE10-浏览器支持给script元素和link元素触发readystatechange事件,用来确定外部的javascript或css文件是否已经加载完成
var script = document.createElement('script'); script.onreadystatechange = function(){ if( script.readyState == 'loaded' || script.readyState == 'complete'){ console.log('loaded'); script.onreadystatechange = null; } } script.src="js/digit.js"; document.body.appendChild(script);
var link = document.createElement('link'); link.rel="stylesheet"; link.onreadystatechange = function(){ if( link.readyState == 'loaded' || link.readyState == 'complete'){ console.log('loaded'); link.onreadystatechange = null; } } link.href="test.css" ; document.getElementsByTagName('body')[0].appendChild(link);