How to Auto Include a Javascript File

Form: 
Author:Mark Kahn

Many developers have a large library of JavaScript code at their fingertips that they developed, their collegues developed, or that they've pieced together from scripts all over the Internet. Have you ever thought that it would be nice to not have to search through all those files just to find that one function? This article will show you how dynamically include any JavaScript file, at runtime, by simply calling a function in that file!

Here's an example: You have a function foo() in file bar.js. In your code, you know that foo() might be called, but it probably won't be because most people do not use its functionality. You don't want to force the user to download bar.js unless it's going to be used because it's a fairly large file. Here you'll learn how to make a fake foo() function that actually loads bar.js on the fly and then calls the real foo() function.

Dynamically Loading a Script
As many developers know, there are at least two different ways to dynamically load a script at runtime. The first is to create a script object and append it to the document. The second is to use an XMLHTTP request to grab the source code, and then eval() it. 

It is this second method that we're going to use, and we're going to exploit the fact that an XMLHTTP request has the capability to completely stall any script activity. 

First, some basics: how to create an XMLHTTP Object. There are as many different functions to return a cross-browser XMLHTTP Object as there are developers that work with AJAX. I happen to have my own as well, and here's a simplified example of that: 

复制代码 代码如下:


function getXMLHttpObj(){ 
  if(typeof(XMLHttpRequest)!='undefined') 
    return new XMLHttpRequest(); 

  var axO=['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.4.0', 
    'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'], i; 
  for(i=0;i<axO.length;i++) 
    try{ 
      return new ActiveXObject(axO[i]); 
    }catch(e){} 
  return null; 


Most browsers other than Internet Explorer 5 or 6 have a built-in XMLHttpRequest object. Internet Explorer 7, when it's released, will also have this object natively. The first thing we do is check to see if this object exists. If it does, we create an instance of it and that's it. If the object doesn't exist, we attempt to create one of several ActiveX Objects. We don't know what objects our users have installed, so we attempt to create several different XMLHTTP objects, starting with the newest ones. 

Now in order to dynamically load functions, we first need to define them. We could do this one function at a time, but instead of hard-coding dozens of functions, we can choose to just make an object or array with all the file names and the functions you want to have auto-included: 

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdxsd.html