Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
一个html文件中包含多个相互依赖的javascript文件_Javascript_Html_Dependency Management - Fatal编程技术网

一个html文件中包含多个相互依赖的javascript文件

一个html文件中包含多个相互依赖的javascript文件,javascript,html,dependency-management,Javascript,Html,Dependency Management,我有两个javascript文件(file1,file2)。File1使用file2中定义的类。我是否能够通过以下方式从html文件中引用这些文件: <script type="text/javascript" src="file1.js"></script> <script type="text/javascript" src="file2.js"></script> 这是否允许file1依赖于file2中定义的类? 如果没有,那么哪些插件

我有两个javascript文件(file1,file2)。File1使用file2中定义的类。我是否能够通过以下方式从html文件中引用这些文件:

<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>

这是否允许file1依赖于file2中定义的类?
如果没有,那么哪些插件允许这种依赖关系?

这与您使用它们的方式有关。简化的方法

场景1:

script1.js

脚本2.js

test.html

如上所述的script2.js和test.html

它不工作(js错误)

场景3:

script1.js

script2.js保持不变

test.html


它起作用了

这就是您要找的吗?

概述:

使用Jquery动态加载JS,方法如下:

$.getScript("file1.js",function(){

    alert("File1.js is loaded");
}
具有面向对象JS和动态JS加载的示例

File1.js作为:

File1 = function(){
}
File1.prototype=
{
    constructor:File1,
    primary:function()
    {
        if (File2 == "undefined")
        {
           $.getScript("file2.js",function()
           {
              file2 = new File2();
              file2.secondary();
           });
        }
    }
}
File2.js作为:

File2 = function(){
}
File2.prototype=
{
  constructor:File2,
  secondary:function()
  {
    if (File1 == "undefined")
    {
      $.getScript("file1.js",functiom()
      {
         file1 = new File1();
         file1.primary();
      });
    }
  }
}

这应该会让您对动态加载JS以及JS面向对象的概念有一个很好的了解。

为什么不先包含file2.JS?听起来您需要签出requireJS如果file1需要file2,那么脚本标记的顺序不应该颠倒吗?除此之外,我也是requirejs的粉丝,但如果你只有这两个文件,那就太过分了。
secondary();
secondary();
<html>
<head>
<script src=script1.js defer></script>
<script src=script2.js></script>
</head>
<body>
</body>
</html>
$.getScript("file1.js",function(){

    alert("File1.js is loaded");
}
File1 = function(){
}
File1.prototype=
{
    constructor:File1,
    primary:function()
    {
        if (File2 == "undefined")
        {
           $.getScript("file2.js",function()
           {
              file2 = new File2();
              file2.secondary();
           });
        }
    }
}
File2 = function(){
}
File2.prototype=
{
  constructor:File2,
  secondary:function()
  {
    if (File1 == "undefined")
    {
      $.getScript("file1.js",functiom()
      {
         file1 = new File1();
         file1.primary();
      });
    }
  }
}