简体   繁体   中英

multiple interdependent javascript files in one html file

I have two javascript files (file1, file2). File1 uses a class defined in file2. Am I able to reference these files from an html file the following manner:

<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? 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:

script1.js

function primary()
{
    secondary();
}

script2.js

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

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:

script1.js

secondary();

script2.js and test.html as above

It's not working (js error)

Scenario 3:

script1.js

secondary();

script2.js remains the same

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:

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

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

Example with Object Oriented JS and dynamic js loading.

File1.js as:

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

File2.js As:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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