代码之家  ›  专栏  ›  技术社区  ›  LUN

我如何将几个js文件中的js代码“包含”到主html文件中?

  •  -2
  • LUN  · 技术社区  · 8 月前

    我在之前的html文件中有很多javascript(js)代码。
    我已经将部分代码移动到另一个js文件中——file1、file2——见下面的代码。
    在搬家之前,我没有考虑函数声明的顺序。还可以。
    移动之后,顺序开始变得重要。

    我用过 defer 属性强制浏览器在开始执行之前下载所有脚本。 但是当主代码开始执行时,浏览器报告了一个错误——文件1/2中的函数没有定义。

    问题是:我如何将一部分js代码移动到另一个js文件中,而不必担心其他文件的包含顺序和主代码中函数声明的顺序?

    html...
     
    <script>
         the main js-code - previously all js-code, including file1 and file2, was placed here
    </script>
     
    <script defer src="file1.js"></script>
    <script defer src="file2.js"></script>
    
    1 回复  |  直到 8 月前
        1
  •  2
  •   fr13nd230    8 月前

    所以现在,当你 将旧函数从script标记内部移动到单独的文件中 . 因此,为了达到与以前相同的结果,有很多方法和策略可以使用,其中之一如下:

    使用模块方法并手动调用您的函数,如下所示:

    <script type="module">
        import { functionFromFile1 } from './file1.js';
        import { functionFromFile2 } from './file2.js';
    
        // Call the functions here without worrying about order
        functionFromFile1();
        functionFromFile2();
    </script>
    

    现在就像在 file(1/2).js 导出函数如下:

    export function functionFromFile1or2() {
    // Your function code goes here.
    }
    

    你会注意到现在没有必要 defer .