How can I dynamically download and run a javascript script from a javascript console?

前端 未结 3 882
死守一世寂寞
死守一世寂寞 2021-02-14 06:26

Is there a one-liner I could execute in a javascript console to download and execute a javascript script from a remote source?

I was looking to see if there was a nic

3条回答
  •  无人共我
    2021-02-14 06:50

    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);  
       }
    }
    

    This works cross-browser.

    edit

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

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

提交回复
热议问题