Didn"t forge 2009-06-04 11:59 采纳率: 25%
浏览 858
已采纳

如何在另一个 JavaScript 文件中包含一个 JavaScript 文件?

Is there something in JavaScript similar to @import in CSS that allows you to include a JavaScript file inside another JavaScript file?

转载于:https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file

  • 写回答

29条回答 默认 最新

  • 三生石@ 2009-06-04 12:13
    关注

    The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

    But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.

    For compatibility with older browsers, build and/or transpilation tools can be used.

    ES6 Modules

    ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag. All files involved must have the .mjs extension.

    // module.mjs
    export function hello() {
      return "Hello";
    }
    
    // main.mjs
    import { hello } from 'module'; // or './module'
    let val = hello();  // val is "Hello";
    

    ECMAScript modules in browsers

    Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse.

    <script type="module">
      import { hello } from './hello.mjs';
      hello('world');
    </script>
    
    // hello.mjs
    export function hello(text) {
      const div = document.createElement('div');
      div.textContent = `Hello ${text}`;
      document.body.appendChild(div);
    }
    

    Read more at: https://jakearchibald.com/2017/es-modules-in-browsers/

    Dynamic imports in browsers

    Dynamic imports let the script load other scripts as needed:

    <script type="module">
      import('hello.mjs').then(module => {
          module.hello('world');
        });
    </script>
    

    Read more at: https://developers.google.com/web/updates/2017/11/dynamic-import

    Node.js require

    The old style of importing modules, still widely used in Node.js, is the module.exports/require system.

    // mymodule.js
    module.exports = {
       hello: function() {
          return "Hello";
       }
    }
    
    // server.js
    const myModule = require('./mymodule');
    let val = myModule.hello(); // val is "Hello"   
    

    There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.

    AJAX Loading

    You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

    jQuery Loading

    The jQuery library provides loading functionality in one line:

    $.getScript("my_lovely_script.js", function() {
       alert("Script loaded but not necessarily executed.");
    });
    

    Dynamic Script Loading

    You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

    The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

    Here is an example of how this could work:

    function dynamicallyLoadScript(url) {
        var script = document.createElement("script");  // create a script DOM node
        script.src = url;  // set its src to the provided URL
    
        document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
    }
    

    This function will add a new <script> tag to end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.

    Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

    Detecting when the script has been executed

    Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

    It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

    For example: my_lovely_script.js contains MySuperObject:

    var js = document.createElement("script");
    
    js.type = "text/javascript";
    js.src = jsFilePath;
    
    document.body.appendChild(js);
    
    var s = new MySuperObject();
    
    Error : MySuperObject is undefined
    

    Then you reload the page hitting <kbd>F5</kbd>. And it works! Confusing...

    So what to do about it ?

    Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

    function loadScript(url, callback)
    {
        // Adding the script tag to the head as suggested before
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
    
        // Then bind the event to the callback function.
        // There are several events for cross browser compatibility.
        script.onreadystatechange = callback;
        script.onload = callback;
    
        // Fire the loading
        head.appendChild(script);
    }
    

    Then you write the code you want to use AFTER the script is loaded in a lambda function:

    var myPrettyCode = function() {
       // Here, do whatever you want
    };
    

    Then you run all that:

    loadScript("my_lovely_script.js", myPrettyCode);
    

    Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There's a great article on Javascript loading in general which discusses this.

    Source Code Merge/Preprocessing

    As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backwards compatibility for older browsers, combine files, minify, perform code splitting etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题