javascript - Including a .js file within a .js file


Translate

This question already has an answer here:



All Answers
  • Translate

    I basically do like this, create new element and attach that to <head>

    var x = document.createElement('script');
    x.src = 'http://example.com/test.js';
    document.getElementsByTagName("head")[0].appendChild(x);
    

    You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

    x.onload=callback_function;
    

  • Translate

    The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.

    Alternatively, you can use DOM to create a <script> tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load event on that script tag.

    This function is based on the functionality of jQuery $.getScript()

    function loadScript(src, f) {
      var head = document.getElementsByTagName("head")[0];
      var script = document.createElement("script");
      script.src = src;
      var done = false;
      script.onload = script.onreadystatechange = function() { 
        // attach to both events for cross browser finish detection:
        if ( !done && (!this.readyState ||
          this.readyState == "loaded" || this.readyState == "complete") ) {
          done = true;
          if (typeof f == 'function') f();
          // cleans up a little memory:
          script.onload = script.onreadystatechange = null;
          head.removeChild(script);
        }
      };
      head.appendChild(script);
    }
    
    // example:
    loadScript('/some-other-script.js', function() { 
       alert('finished loading');
       finishSetup();
     });
    

  • Translate

    There is no straight forward way of doing this.

    What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

    Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

    My favorite is(not applicable always):

    <script src="dojo.js" type="text/javascript">
    dojo.require("dojo.aDojoPackage");
    

    Google's closure also provides similar functionality.


  • Translate

    A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.

    Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.

    You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.


  • Translate

    I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

    if (horus.script.broken) {
        document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
        horus.script.loaded(script);
    } else {
        var s=document.createElement('script');
        s.type='text/javascript';
        s.src=script;
        s.async=true;
    
        if (horus.brokenDOM){
            s.onreadystatechange=
                function () {
                    if (this.readyState=='loaded' || this.readyState=='complete'){
                        horus.script.loaded(script);
                    }
            }
        }else{
            s.onload=function () { horus.script.loaded(script) };
        }
    
        document.head.appendChild(s);
    }
    

    where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).