How to dynamically load and use/call a JavaScript file?

前端 未结 4 1147
萌比男神i
萌比男神i 2020-11-30 13:29

I need to dynamically load a JavaScript file and then access its content.

File test.js

test = function () {
    var pub = {}
    pub.def         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 13:39

    There is a great article which is worth reading for all the guys interesting in js script loading in www.html5rocks.com - Deep dive into the murky waters of script loading .

    In that article after considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts thus speeding page loading time.

    But, the author propose another good alternate solution for those people who are desperate to load and execute scripts asynchronously.

    Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:

    [
      'script1.js',
      'script2.js',
      'script3.js',
      'script4.js'
    ].forEach(function(src) {
      var script = document.createElement('script');
      script.src = src;
      script.async = false;
      document.head.appendChild(script);
    });
    

    Now, Spec says: Download together, execute in order as soon as all download.

    Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.

    Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.

    IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.

    Everything else says: I’m your friend, we’re going to do this by the book.

    Now, the full code with IE < 10 workaround:

    var scripts = [
      'script1.js',
      'script2.js',
      'script3.js',
      'script4.js'
    ];
    var src;
    var script;
    var pendingScripts = [];
    var firstScript = document.scripts[0];
    
    // Watch scripts load in IE
    function stateChange() {
      // Execute as many scripts in order as we can
      var pendingScript;
      while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
        pendingScript = pendingScripts.shift();
        // avoid future loading events from this script (eg, if src changes)
        pendingScript.onreadystatechange = null;
        // can't just appendChild, old IE bug if element isn't closed
        firstScript.parentNode.insertBefore(pendingScript, firstScript);
      }
    }
    
    // loop through our script urls
    while (src = scripts.shift()) {
      if ('async' in firstScript) { // modern browsers
        script = document.createElement('script');
        script.async = false;
        script.src = src;
        document.head.appendChild(script);
      }
      else if (firstScript.readyState) { // IE<10
        // create a script and add it to our todo pile
        script = document.createElement('script');
        pendingScripts.push(script);
        // listen for state changes
        script.onreadystatechange = stateChange;
        // must set src AFTER adding onreadystatechange listener
        // else we’ll miss the loaded event for cached scripts
        script.src = src;
      }
      else { // fall back to defer
        document.write('
    
                                     
                  
提交回复
热议问题