且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从javascript控制台动态下载并运行JavaScript脚本?

更新时间:2023-12-05 17:54:16

我写了一个小脚本对于那个。

I've written a little script for that.

var loadjQuery = function(cb){
   if(typeof(jQuery) == 'undefined'){
     var scr = document.createElement('script');
     scr.setAttribute('type', 'text/javascript');
     scr.setAttribute('src', 'http://code.jquery.com/jquery-latest.js');

     if(scr.readyState){
        scr.onreadystatechange = function(){
            if(scr.readyState === 'complete' || scr.readyState === 'loaded'){
               scr.onreadystatechange = null;
               if(cb === 'function'){
                  args = [].slice.call(arguments, 1);
                  cb.apply(this, args);
               }
            }
        };
     }
     else {
        scr.onload = function(){
           if(cb === 'function'){
              args = [].slice.call(arguments, 1);
              cb.apply(this, args);
           }
        };
     }

     var head = document.getElementsByTagName('head')[0];
     head.insertBefore(scr, head.firstChild);  
   }
}

这个工具跨浏览器。

编辑

我已经将该脚本作为一个回调函数。摘要应该是:

I've updated that script as a function with a callback. Synopsis should be:

loadjQuery(function(something){
    // execute code after library was loaded & executed
});