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 相关文章推荐
读jQuery之九 一些瑕疵说明
Jun 21 Javascript
Jquery 点击按钮自动高亮实现原理及代码
Apr 25 Javascript
js实现Select下拉框具有输入功能的方法
Feb 06 Javascript
Javascript中的匿名函数与封装介绍
Mar 15 Javascript
详解JavaScript的回调函数
Nov 20 Javascript
鼠标经过出现气泡框的简单实例
Mar 17 Javascript
详谈表单格式化插件jquery.serializeJSON
Jun 23 jQuery
Bootstrap Table 在指定列中添加下拉框控件并获取所选值
Jul 31 Javascript
JS 中document.write()的用法和清空的原因浅析
Dec 04 Javascript
原生JavaScript实现日历功能代码实例(无引用Jq)
Sep 23 Javascript
JS+CSS实现随机点名(实例代码)
Nov 04 Javascript
javaScript中indexOf用法技巧
Nov 26 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
Windows下PHP的任意文件执行漏洞
2006/10/09 PHP
PHP时间戳 strtotime()使用方法和技巧
2013/10/29 PHP
php中使用session_set_save_handler()函数把session保存到MySQL数据库实例
2014/11/06 PHP
php实现压缩多个CSS与JS文件的方法
2014/11/11 PHP
PHP将session信息存储到数据库的类实例
2015/03/04 PHP
php并发加锁示例
2016/10/17 PHP
TP5.0框架实现无限极回复功能的方法分析
2019/05/04 PHP
javascript与CSS复习(二)
2010/06/29 Javascript
中国地区三级联动下拉菜单效果分析
2012/11/15 Javascript
jQuery淡入淡出元素让其效果更为生动
2014/09/01 Javascript
百度地图api如何使用
2015/08/03 Javascript
jQuery入门基础知识学习指南
2015/08/14 Javascript
jQuery中deferred对象使用方法详解
2016/07/14 Javascript
js滚轮事件兼容性问题需要注意哪些
2016/11/15 Javascript
Vue动态实现评分效果
2017/05/24 Javascript
在vue中获取dom元素内容的方法
2017/07/10 Javascript
基于BootStrap的文本编辑器组件Summernote
2017/10/27 Javascript
iview table render集成switch开关的实例
2018/03/14 Javascript
微信小程序绑定手机号获取验证码功能
2019/10/22 Javascript
JS实现简单的表格增删
2020/01/16 Javascript
Python使用scrapy采集数据过程中放回下载过大页面的方法
2015/04/08 Python
python动态网页批量爬取
2016/02/14 Python
浅谈五大Python Web框架
2017/03/20 Python
Python异常处理知识点总结
2019/02/18 Python
Django中如何防范CSRF跨站点请求伪造攻击的实现
2019/04/28 Python
Django stark组件使用及原理详解
2019/08/22 Python
如何理解python面向对象编程
2020/06/01 Python
英国工艺品购物网站:Minerva Crafts
2018/01/29 全球购物
美国女士时尚珠宝及配饰购物网站:Icing
2018/07/02 全球购物
创业计划书如何编写
2014/02/06 职场文书
2014年秋季开学典礼致辞
2014/08/02 职场文书
酒会开场白大全
2015/06/01 职场文书
2016年寒假社会实践活动心得体会
2015/10/09 职场文书
自考生自我评价
2019/06/21 职场文书
python使用glob检索文件的操作
2021/05/20 Python
Java用自带的Image IO给图片添加水印
2021/06/15 Java/Android