简体   繁体   English

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

[英]multiple interdependent javascript files in one html file

I have two javascript files (file1, file2). 我有两个JavaScript文件(文件1,文件2)。 File1 uses a class defined in file2. File1使用在file2中定义的类。 Am I able to reference these files from an html file the following manner: 我是否可以通过以下方式从html文件引用这些文件:

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

Will this allow for file1's dependence upon the class defined in file2? 这会允许file1依赖于file2中定义的类吗? If not what are some plugins that do allow for this sort of dependency? 如果不是,那么哪些插件允许这种依赖性?

It has to do with the way you are going to use them. 它与您使用它们的方式有关。 A simplified approach. 一种简化的方法。

Scenario 1: 方案1:

script1.js script1.js

function primary()
{
    secondary();
}

script2.js script2.js

function secondary()
{
    alert("hi primary");
}

test.html test.html

<html>
<head>
<script src=script1.js></script>
<script src=script2.js></script>
</head>
<body>
</body>
</html>

It works (you already know it) 它有效(您已经知道了)

Scenario 2: 方案2:

script1.js script1.js

secondary();

script2.js and test.html as above 如上所述的script2.js和test.html

It's not working (js error) 它不起作用(js错误)

Scenario 3: 方案3:

script1.js script1.js

secondary();

script2.js remains the same script2.js保持不变

test.html test.html

<html>
<head>
<script src=script1.js defer></script>
<script src=script2.js></script>
</head>
<body>
</body>
</html>

It works. 有用。

Is this what you're looking for? 这是您要找的东西吗?

Overview: 概述:

Use Jquery to load JS dynamically using the following: 使用Jquery通过以下方式动态加载JS:

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

    alert("File1.js is loaded");
}

Example with Object Oriented JS and dynamic js loading. 面向对象JS和动态JS加载的示例。

File1.js as: File1.js为:

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

File2.js As: File2.js为:

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

This should give you pretty good idea of dynamic loading of JS, and JS Object oriented concept as well. 这应该使您对动态加载JS以及JS面向对象的概念有一个很好的了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM