How to Auto Include a Javascript File


Posted in Javascript onFebruary 02, 2007

Form: http://www.webreference.com/programming/javascript/mk/
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: 

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]);  
} 
The loadScript function expects two arguments: scriptpath and functions. "scriptpath" should contain the URL to your JavaScript file, and "functions" is the array of functions that exist in this JavaScript file.

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. 

Javascript 相关文章推荐
JavaScript RegExp方法获取地址栏参数(面向对象)
Mar 10 Javascript
JS Jquery 遍历,筛选页面元素 自动完成(实现代码)
Jul 08 Javascript
简易的投票系统以及js刷票思路和方法
Apr 07 Javascript
利用Angularjs和原生JS分别实现动态效果的输入框
Sep 01 Javascript
聊一聊JS中的prototype
Sep 29 Javascript
bootstrap下拉列表与输入框组结合的样式调整
Oct 08 Javascript
详解js界面跳转与值传递
Nov 22 Javascript
jQuery实现Select下拉列表进行状态选择功能
Mar 30 jQuery
浅析vue 函数配置项watch及函数 $watch 源码分享
Nov 22 Javascript
vue router 用户登陆功能的实例代码
Apr 24 Javascript
Node.js使用MongoDB的ObjectId作为查询条件的方法
Sep 10 Javascript
ES6实现图片切换特效代码
Jan 14 Javascript
Code:loadScript( )加载js的功能函数
Feb 02 #Javascript
JavaScript脚本性能的优化方法
Feb 02 #Javascript
JavaScript中“+=”的应用
Feb 02 #Javascript
HTTP状态代码以及定义(解释)
Feb 02 #Javascript
任意位置显示html菜单
Feb 01 #Javascript
Javascript 判断 object 的特定类转载
Feb 01 #Javascript
背景音乐每次刷新都可以自动更换
Feb 01 #Javascript
You might like
PHP 杂谈《重构-改善既有代码的设计》之五 简化函数调用
2012/05/07 PHP
PHP关联数组实现根据元素值删除元素的方法
2015/06/26 PHP
浅谈PHP中类和对象的相关函数
2017/04/26 PHP
A标签触发onclick事件而不跳转的多种解决方法
2013/06/27 Javascript
JavaScript判断变量是否为undefined的两种写法区别
2013/12/04 Javascript
JS兼容浏览器的导出Excel(CSV)文件的方法
2014/05/03 Javascript
jquery实现图片水平滚动效果代码分享
2015/08/26 Javascript
原生javascript实现解析XML文档与字符串
2016/03/01 Javascript
jQuery控制div实现随滚动条滚动效果
2016/06/07 Javascript
javascript的replace方法结合正则使用实例总结
2016/06/16 Javascript
微信小程序 绘图之饼图实现
2016/10/24 Javascript
浅谈jQuery操作类数组的工具方法
2016/12/23 Javascript
详解使用fetch发送post请求时的参数处理
2017/04/05 Javascript
React.js中常用的ES6写法总结(推荐)
2017/05/09 Javascript
React-Native 组件之 Modal的使用详解
2017/08/08 Javascript
JS实现的简单四则运算计算器功能示例
2017/09/27 Javascript
在vscode中统一vue编码风格的方法
2018/02/22 Javascript
使用layer弹窗和layui表单实现新增功能
2018/08/09 Javascript
vue通过指令(directives)实现点击空白处收起下拉框
2018/12/06 Javascript
vue缓存的keepalive页面刷新数据的方法
2019/04/23 Javascript
ES6中Set和Map用法实例详解
2020/03/02 Javascript
微信小程序scroll-view的滚动条设置实现
2020/03/02 Javascript
[01:48:04]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant BO3 第一场 2月7日
2021/03/11 DOTA
深入解析Python中的lambda表达式的用法
2015/08/28 Python
python-itchat 统计微信群、好友数量,及原始消息数据的实例
2019/02/21 Python
Selenium启动Chrome时配置选项详解
2020/03/18 Python
Python如何实现FTP功能
2020/05/28 Python
如何用 Python 制作 GitHub 消息助手
2021/02/20 Python
Pytorch - TORCH.NN.INIT 参数初始化的操作
2021/02/27 Python
大学信息公开实施方案
2014/03/09 职场文书
积极贯彻学习两会精神总结
2014/03/17 职场文书
期中考试反思800字
2014/05/01 职场文书
中学教师个人总结
2015/02/10 职场文书
二手房购房意向书
2015/05/09 职场文书
2015年班主任德育工作总结
2015/05/21 职场文书
关于python中模块和重载的问题
2021/11/02 Python