`

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>
 

 

 

 

分享到:
评论

相关推荐

    divide and conquer 2.zip_algorithm_conquer_divide and conquer

    分治法(Divide and Conquer)是计算机科学中一种重要的算法思想,它的核心理念在于将一个复杂的问题分解成若干个规模较小、相互独立、与原问题形式相同的子问题,然后分别解决这些子问题,最后将子问题的解组合起来...

    BigDecimal.js.zip

    总之,BigDecimal.js是一个强大的JavaScript库,专门用于处理大数的高精度计算,通过引入"BigDecimal-all-last.min.js",开发者可以获得精确的大数运算能力,从而避免JavaScript原生数据类型的精度问题。在开发过程...

    python-divide-and-conquer.rar

    python-divide_and_conquer.rar

    计算模型与算法技术:4-Divide-and-Conquer.ppt

    计算模型与算法技术:4-Divide-and-Conquer.ppt

    [MMS_053014]Divide LINT by DINT.rar

    本资料“[MMS_053014]Divide LINT by DINT.rar”显然是一个关于AB PLC编程的教程或示例程序,重点在于讲解如何在LINT(Long Integer,长整型)数据类型和DINT(Double Integer,双整型)数据类型之间进行除法运算。...

    js库bignumber.js_v9.0.2

    `bignumber.js_v9.0.2`是这样一个高效、易用的JavaScript库,它提供了处理大数的能力,确保了计算的精确性。 ### 一、JavaScript的Number类型限制 JavaScript的Number类型实际上是一种IEEE 754双精度浮点数,它...

    算法设计技巧与分析课件(英文版):ch6 Divide and Conquer.ppt

    算法设计技巧与分析课件(英文版):ch6 Divide and Conquer.ppt

    js-leetcode题解之29-divide-two-integers.js

    js js_leetcode题解之29-divide-two-integers.js

    Data.Structures.and.Algorithms.Made.Easy.epub

    There are multiple solutions for each problem and the book is coded in C/C++, it comes handy as an interview and exam guide for computer scientists. A handy guide of sorts for any computer science ...

    javascript版BigDecimal类库

    2. **算术操作**:提供加法(`add`)、减法(`subtract`)、乘法(`multiply`)、除法(`divide`)等基本算术运算,这些操作能确保结果的精度不受JavaScript Number类型的限制。 3. **比较操作**:支持小于(`lt`)...

    Python库 | divide-4.tar.gz

    本资源“divide-4.tar.gz”是一个压缩包,其中包含了一个名为“divide-4”的Python库。这个库可能专注于数值计算,特别是与除法操作相关的功能,因为“divide”通常与数学中的除法概念相关联。下面我们将详细探讨...

    数据结构与算法 JavaScript 描述. 章节练习.zip

    6. 分治策略(Divide and Conquer):将大问题分解为小问题求解,如归并排序、快速排序等。 在"数据结构与算法 JavaScript 章节练习.zip"这个压缩包中,可能包含了上述数据结构和算法的相关练习题目和解答,帮助...

    Divide and Conquer, Sorting and Searching, and Randomized Algorithms python 版答案

    斯坦福algorithm part1 Divide and Conquer, Sorting and Searching, and Randomized Algorithms python 版答案

    Data.Structures.and.Algorithms.USING.C

    With a strong emphasis on structured design and programming techniques, it features precise instructions on all the steps involved in data structure development-from theoretical conception to ...

    Bigdecimal.js

    "Bigdecimal.js"就是这样一个专门解决多精度小数运算问题的JavaScript库。它允许开发者在JavaScript环境中进行高精度的浮点数运算,避免了由于JavaScript内置类型处理大数和小数时可能出现的精度丢失问题。 ...

    JS处理货币格式浮点数插件currency.js.zip

    在JavaScript(JS)中,处理货币格式的浮点数是一个常见的需求,特别是在电子商务网站和财务应用中。`currency.js` 是一个专为这个目的设计的插件,它可以帮助开发者更方便、更精确地格式化和操作货币数值。下面将...

Global site tag (gtag.js) - Google Analytics