Javascript divide and load multiple .js files

It is a common practise to  divide the programming code into multiple files.  the same principle/rule/doctrin also applies to Javascript. 

 

you may have a .htm file and several modules, each module in its own .js file.  the problem here is how to load the the separate modules into the html file.

 

there are generally two strategies.

 

 

  • statically load modules
  • dynamically load modules.

 

statically load moduels

 

Statically load modules approach is useful when you know in advance which modules will be loaded and the modules will not change.

 

to do that, you simple do the following..

 

 

<script src="file1.js"></script>
<script src="file2.js"></script>
<script src="file3.js"></script>
<script src="file4.js"></script>
 

 

 

Or you can do the following.

 

 

 

<script src="file.js"></script>

 

 

and the content of the file.js is something like this:

 

 

document.write('<script src="file1.js"><\/script>');
document.write('<script src="file2.js"><\/script>');
document.write('<script src="file3.js"><\/script>');
document.write('<script src="file4.js"><\/script>');
 

 

NOTE: Common Pitfall

 

there is a common snag/snare that people might accidently fallen into. Let me illustrate that with a simple example.

 

 

first, we defined some unit test code, and store it in a file called js/unit.js, the conte of the file is.

 

 

/**
* @Name
* @Comment: add global function to do unit test 
*/
(function () {
  var results;
  this.assert = function assert(value, desc) {
    var li = document.createElement("li");
    // note, this is DOM specification 2, which it may not be suppported by the Editor, but should be fine, let me know if otherwise.
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    results.appendChild(li);
    if (!value) {
      li.parentNode.parentNode.className = "fail";
    }
    return li;
  };
  this.test = function test(name, fn) {
    results = document.getElementById("results");
    results = assert(true, name).appendChild(
                  document.createElement("ul"));
    fn();
  };
})();
 

 

and we have a file, which demonstrate how to use an object to simuate an arrary, in "js/fakeArrayMethod.js", contents as 

 

 

 

/**
* @Comment: this fake array methods and treat a normal object as an array 
*/

var elems = {
  // I think the find is the key to array[idx]??
  find: function (id) {
    this.add(document.getElementById(id));
  },
  // the length is the stub to the count given by array.length?
  length: 0,
  // while this is how you update the lengh property
  add: function (elem) {
    Array.prototype.push.call(this, elem);
  }
};
 

the content of the test file, "fakeArrayMethod.htm" has the following content.

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript" src="js/unit.js" ></script>
    <!-- is that a bug, if you do this, 

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

    then nothing is displayed, but if you change to this, you can ?


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


    -->
   <script type="text/javascript" src="js/fakeArrayMethod.js"></script>

    <script type="text/javascript">
      window.onload = function () {
        test("A test.", function () {
          assert(true, "First assertion completed");
          assert(true, "Second assertion completed");
          assert(true, "Third assertion completed");  
        });

        test("FakeArrayMethod", function () {
          elems.find("first");

          assert(elems.length == 1 && elems[0].nodeType,
          "Verify that we have an element in our stash");

          elems.find("second");

          assert(elems.length == 2 && elems[0].nodeType, "Verify the other insertion");

        });


      };

    </script>
    <style type="text/css">
        #results li.pass { color: green; }
        #results li.fail { color: red; }
    </style>
</head>
<body>
<input id="first" />
<input id="second" />
    <ul id="results"></ul>
</body>
</html>
 

As described in the above comment, there is  comment saying that if you have the script tag as follow, then, the program will not work correctly. so 

 

 

 

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

 

will not be intepret by the runtime correctly, but if you have this 

 

 

 

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

 

then it is correct.

Dynamically load moduels

 

In this post, How to split JavaScript code into multiple files and use them without including them via script tag in HTML? it introduced several ways that you can import some js modules dynamically. 

 

 

and in another post titled 4 ways to dynamically load external JavaScript(with source)  it discussed several ways to dynamically load external javascript.

 

 

 

they are 

 

 

  • using document.write 
  • Dynamically change the src property value
  • Dynamically create <script > element
  • Get Javascript by using XMLHttp, then create script object.

 

 

 

choice 1: using document.write 

 

 

// you need to put an escape character before the closing </script> tag, like this: <\/script>
<script language="javascript">
document.write("<script src='other.js'><\/script>");
</script>
 

 

 

 

choice 2: Dynamically change the src property value

 

 

 

<script src='' id="s1"></script>
<script language="javascript">
s1.src="other.js"
</script>
 

 

 

 

 

choice 3: Dynamically create <script> element

 

 

<script>
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="other.js";
oHead.appendChild( oScript);
</script>
 

choice 4: Get JavaScript by using XMLHTTP,then create script object


<script language="JavaScript">
function GetHttpRequest()
{
if ( window.XMLHttpRequest ) // Gecko
return new XMLHttpRequest() ;
else if ( window.ActiveXObject ) // IE
return new ActiveXObject("MsXml2.XmlHttp") ;
}
function AjaxPage(sId, url){
var oXmlHttp = GetHttpRequest() ;
oXmlHttp.OnReadyStateChange = function()
{
if ( oXmlHttp.readyState == 4 )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
{
IncludeJS( sId, url, oXmlHttp.responseText );
}
else
{
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
oXmlHttp.open('GET', url, true);
oXmlHttp.send(null);
}
function IncludeJS(sId, fileUrl, source)
{
if ( ( source != null ) && ( !document.getElementById( sId ) ) ){
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement( "script" );
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = true;
oScript.text = source;
oHead.appendChild( oScript );
}
}
AjaxPage( "scrA", "b.js" );
alert( "dynamically load javascript");
alert( "dynamically load a.js and get the variable:" + str );
</script>
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值