我正在读这本书:第三方Javascript :
有一个示例代码:(加载外部js)
(function ()
{
var script = document.createElement('script');
script.async = true;
script.src = 'js_file.js';
script.onload = script.onreadystatechange = function ()
{
var rdyState = script.readyState;
if (!rdyState || /loaded|complete/.test(rdyState))
{
/*...*/
script.onload = null;
script.onreadystatechange = null;
}
};
var entry = document.getElementsByTagName('script')[0];
entry.parentNode.insertBefore(script, entry);
})();
我正在努力理解这一行:
if (!rdyState || /loaded|complete/.test(rdyState))...
我在undefined
script.readyState
问题:
undefined
收到script.readyState
?http://jsbin.com/ipOrIDeY/4/edit
(Chrome 31.感谢Google,但不要感谢字体平滑版。(32))
答案 0 :(得分:1)
这是我加载javascript文件的代码,它工作得很好,readystate返回字符串,但它的值取决于你的javascript引擎。
var n = document.createElement('script');
n.setAttribute('type', 'text/javascript');
n.setAttribute('src', 'Your src');
n.setAttribute('async', true);
n.onerror = function() {
callback()
n.onerror = null;
};
n.onload = n.onreadystatechange = function() {
if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
callback()
n.onload = n.onreadystatechange = null;
}
};
document.body.appendChild(n);