动态加载javascript/json然后立即执行

作者:半瓶墨水 链接:http://www.2maomao.com/blog/load-javascript-dynamically/

晚上想写个json接口,类似delicious的那种webapi。

Python讨论组里有人建议替换已经加载的脚本的src属性,或者重新生成一个script然后加载。

但是这种方式为异步加载,也就是浏览器想啥时候加载完咱不知道,想要加载以后立即进行操作的就不能保证了。

Google一下动态加载javascript找到一大堆,看起来用XMLHttpRequest应该可行,试了一下,搞定了:

function change_style(style) {
    
var oXmlHttp = GetHttpRequest() ;
    
oXmlHttp.onreadystatechange = function()
    
{
        
if ( oXmlHttp.readyState == 4 )
        
{
            
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
            
{
                
txt = oXmlHttp.responseText;
                
alert(txt)
                
var oScript = document.createElement( "script" );
                
oScript.language = "javascript";
                
oScript.type = "text/javascript";
                
oScript.id = sId;
                
oScript.defer = true;
                
oScript.text = source;
                
document.body.appendChild( oScript );
            
}
            
else
            
{
                
alert('操作失败:' + oXmlHttp.statusText + '(' + oXmlHttp.status + ')' ) ;
            
}
        
}
    
}
 
    
url = 'http://127.0.0.1:8000/static/styles/pyg/' + style + '.js';
    
oXmlHttp.open('GET', url, true);
    
oXmlHttp.send(null);
}

这里有个更简单的方法(未验证),加载后执行一个helper函数,呵呵:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
    
if (this.readyState == 'complete') helper();
}
script.onload = helper;
script.src = 'helper.js';
head.appendChild(script);

555,本篇现在一条评论也没有,雁过留声,人过留名,各位乡亲父老,有钱的捧个钱场,没钱的捧个人场......

发表评论

  • :(
  • :)
  • :D
  • :X
  • :^
  • :d
  • :e
  • :h
  • :k
  • :l
  • :p
  • :q
  • :s
  • :v
  • :w
  • :x

注意:评论中需包含至少一个中文字,否则视为无效