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 相关文章推荐
简单js代码实现selece二级联动(推荐)
Feb 18 Javascript
js style动态设置table高度
Oct 21 Javascript
jQuery表格插件datatables用法详解
Nov 23 Javascript
详解AngularJS如何实现跨域请求
Aug 22 Javascript
js字符串与Unicode编码互相转换
May 17 Javascript
echarts学习笔记之图表自适应问题详解
Nov 22 Javascript
基于Angular中ng-controller父子级嵌套的相关属性详解
Oct 08 Javascript
构建大型 Vue.js 项目的10条建议(小结)
Nov 14 Javascript
JavaScript实现文件下载并重命名代码实例
Dec 12 Javascript
JS async 函数的含义和用法实例总结
Apr 08 Javascript
原生js实现日期选择插件
May 21 Javascript
vue项目打包后路由错误的解决方法
Apr 13 Vue.js
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
APMServ使用说明
2006/10/23 PHP
jQuery EasyUI API 中文文档 - DateBox日期框
2011/10/15 PHP
点图片上一页下一页翻页效果
2008/07/09 Javascript
Extjs4 消息框去掉关闭按钮(类似Ext.Msg.alert)
2013/04/02 Javascript
用显卡加速,轻松把笔记本打造成取暖器的办法!
2013/04/17 Javascript
js中confirm实现执行操作前弹出确认框的方法
2014/11/01 Javascript
JS制作手机端自适应缩放显示
2015/06/11 Javascript
jQuery实现可高亮显示的二级CSS菜单效果
2015/09/01 Javascript
nodejs初步体验篇
2015/11/23 NodeJs
对象转换为原始值的实现方法
2016/06/06 Javascript
jQuery手指滑动轮播效果
2016/12/22 Javascript
微信小程序学习之数据处理详解
2017/07/05 Javascript
Vue2 SSR渲染根据不同页面修改 meta
2017/11/20 Javascript
three.js实现3D影院的原理的代码分析
2017/12/18 Javascript
laravel5.3 vue 实现收藏夹功能实例详解
2018/01/21 Javascript
vue filters的使用详解
2018/06/11 Javascript
JavaScript中七种流行的开源机器学习框架
2018/10/11 Javascript
js实现多张图片每隔一秒切换一张图片
2019/07/29 Javascript
vue移动端的左右滑动事件详解
2020/06/17 Javascript
浅谈Python单向链表的实现
2015/12/24 Python
python简单实例训练(21~30)
2017/11/15 Python
anaconda如何查看并管理python环境
2019/07/05 Python
Python使用selenium + headless chrome获取网页内容的方法示例
2019/10/16 Python
jupyter notebook 的工作空间设置操作
2020/04/20 Python
带有css3动画效果的兼容多浏览器简单导航条示例
2014/01/26 HTML / CSS
HTML5进度条特效
2014/12/18 HTML / CSS
Evisu官方网站:日本牛仔品牌,时尚街头设计风格
2016/12/30 全球购物
什么是WEB控件?使用WEB控件有哪些优势?
2012/01/21 面试题
小学教师听课制度
2014/02/01 职场文书
擅自离岗检讨书
2014/02/11 职场文书
社区综治宣传月活动总结
2014/07/02 职场文书
运动会广播稿150字(9篇)
2014/09/20 职场文书
公司离职证明标准范本
2014/10/05 职场文书
车间统计员岗位职责
2015/04/14 职场文书
2015年大学生村官工作总结
2015/04/21 职场文书
面试复试通知单
2015/04/24 职场文书