Including a .js file within a .js file

This question already has an answer here:

  • How do I include a JavaScript file in another JavaScript file? 50 answers

  • 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;
    

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

    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.

    链接地址: http://www.djcxy.com/p/7330.html

    上一篇: “包含”一个JavaScript文件到另一个

    下一篇: 在.js文件中包含.js文件