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 类与静态类的实现
Apr 01 Javascript
Javascript实现的类似Google的Div拖动效果代码
Aug 09 Javascript
Javascript处理DOM元素事件实现代码
May 23 Javascript
jQuery替换字符串(实例代码)
Nov 13 Javascript
jquery 检测元素是否存在的实例代码
Nov 19 Javascript
JS中attr和prop属性的区别以及优先选择示例介绍
Jun 30 Javascript
分享一些常用的jQuery动画事件和动画函数
Nov 27 Javascript
用AngularJS来实现监察表单按钮的禁用效果
Nov 02 Javascript
微信小程序 蓝牙的实现实例代码
Jun 27 Javascript
jQuery中将json数据显示到页面表格的方法
May 27 jQuery
VUE.js实现动态设置输入框disabled属性
Oct 28 Javascript
vue-i18n实现中英文切换的方法
Jul 06 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中的超全局变量
2006/10/09 PHP
php中批量修改文件后缀名的函数代码
2011/10/23 PHP
thinkPHP使用post方式查询时分页失效的解决方法
2015/12/09 PHP
基于laravel-admin 后台 列表标签背景的使用方法
2019/10/03 PHP
javascript中巧用“闭包”实现程序的暂停执行功能
2007/04/04 Javascript
js href的用法
2010/05/13 Javascript
jquery自定义类似$.ajax()的方法实现代码
2013/08/13 Javascript
深入学习jQuery Validate表单验证(二)
2016/01/18 Javascript
js实现前端分页页码管理
2017/01/06 Javascript
Vue学习笔记进阶篇之单元素过度
2017/07/19 Javascript
微信小程序使用checkbox显示多项选择框功能【附源码下载】
2017/12/11 Javascript
如何提升vue.js中大型数据的性能
2019/06/21 Javascript
JS+Canvas实现五子棋游戏
2020/08/26 Javascript
使用AutoJs实现微信抢红包的代码
2020/12/31 Javascript
[01:37]DOTA2超级联赛专访ChuaN 传奇般的电竞之路
2013/06/19 DOTA
python通过post提交数据的方法
2015/05/06 Python
python使用PyCharm进行远程开发和调试
2017/11/02 Python
详解Django的CSRF认证实现
2018/10/09 Python
用python生成1000个txt文件的方法
2018/10/25 Python
Python3.5运算符操作实例详解
2019/04/25 Python
python 批量添加的button 使用同一点击事件的方法
2019/07/17 Python
django model通过字典更新数据实例
2020/04/01 Python
python基于selenium爬取斗鱼弹幕
2021/02/20 Python
妇产科护士自我鉴定
2013/10/15 职场文书
建筑班组长岗位职责
2014/01/02 职场文书
出国留学介绍信
2014/01/13 职场文书
手术室护士长竞聘书
2014/03/31 职场文书
减负增效提质方案
2014/05/23 职场文书
教师三严三实对照检查材料
2014/09/25 职场文书
保洁员岗位职责
2015/02/04 职场文书
应届毕业生求职信范文
2015/03/19 职场文书
2015年电气技术员工作总结
2015/07/24 职场文书
导游词之山东红叶谷
2019/10/31 职场文书
浅谈Redis存储数据类型及存取值方法
2021/05/08 Redis
详解Vue router路由
2021/11/20 Vue.js
SQL Server 忘记密码以及重新添加新账号
2022/04/26 SQL Server