var autoIncludeFunctions = {
'scripts/file1.js': ['function1', 'function2', 'function3'],
'scripts/file2.js': ['function4', 'function5', 'function6'],
'scripts/file3.js': ['function7', 'function8', 'function9']
}
Our autoIncludeFunctions object should contain a list of JavaScript files, as well as a list of functions in those files. Here we are using shorthand JavaScript notation to create both the object and the arrays, but the same thing could be accomplished in many different ways.
These .js files can contain any code you have available, such as JavaScript menus, animations, etc. The simplest example would be a file titled "file1.js" that only contained "function function1(){ alert('Hello, World!'); }".
Note that if any of these files contain functions with the same name as another file, only the last function listed will be used.
To make things a bit easier, we're going to make a function that will pull a JavaScript file down and execute it. It's very important, in our case, that the third paramater sent to the XMLHTTP object be false. This forces the script to wait for the response to download as opposed to continuing on with other code.
复制代码 代码如下:
function loadScript(scriptpath, functions){
var oXML = getXMLHttpObj();
oXML.open('GET', scriptpath, false);
oXML.send('');
eval(oXML.responseText);
for(var i=0; i<functions.length; i++)
window[functions[i]] = eval(functions[i]);
}
As you can see, the code to pull and execute a script is straightforward. The browser first downloads, and then interprets the JavaScript file. If you've read any other articles on AJAX development, you might remember that in most cases the third argument sent to the open() function of an XMLHTTP object is usually "true." In our case we have it set to "false." This argument controls the state of the XMLHTTP object. If set to true, the object runs asynchrounously, meaning that all other JavaScript code continues while the object is loading. While this is a good thing in many circumstances, if we implemented it here our code would return before our file was done loading. Since we want our code to wait until this file is complete, we set this third argument to false, thus pausing our JavaScript execution until we are ready to continue.
When the code is evaluated from the responseText, it's executed in the limited scope of the loadScript function and because of this, none of these functions will be available outside of the loadScript function. In order do get around this, the for loop adds each function to the window object, thus making it globally available.
It's important to note that only scripts on the same server as the current page can be called in this manner. This is inherent to the XMLHTTP Object and is a necessary measure to increase general browser security.