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 相关文章推荐
根据分辨率不同,调用不同的css文件
Jul 07 Javascript
利用JQuery+EasyDrag 实现弹出可拖动的Div,同时向Div传值,然后返回Div选中的值
Oct 24 Javascript
分享9点个人认为比较重要的javascript 编程技巧
Apr 27 Javascript
基于JS实现横线提示输入验证码随验证码输入消失(js验证码的实现)
Oct 27 Javascript
jQuery插件HighCharts绘制2D带Label的折线图效果示例【附demo源码下载】
Mar 08 Javascript
vue实现表格增删改查效果的实例代码
Jul 18 Javascript
vue项目webpack中Npm传递参数配置不同域名接口
Jun 15 Javascript
微信小程序基于picker实现级联菜单
Feb 15 Javascript
Vue-Cli项目优化操作的实现
Oct 27 Javascript
微信小程序获取公众号文章列表及显示文章的示例代码
Mar 10 Javascript
jQuery HTML获取内容和属性操作实例分析
May 20 jQuery
vue中使用echarts的示例
Jan 03 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
PHP return语句另类用法不止是在函数中
2014/09/17 PHP
学习php设计模式 php实现观察者模式(Observer)
2015/12/09 PHP
一键生成各种尺寸Icon的php脚本(实例)
2017/02/08 PHP
[原创]php正则删除html代码中class样式属性的方法
2017/05/24 PHP
php+redis消息队列实现抢购功能
2018/02/08 PHP
仿jQuery的siblings效果的js代码
2011/08/09 Javascript
JS中不为人知的五种声明Number的方式简要概述
2013/02/22 Javascript
JS对文本框值的判断示例
2014/03/10 Javascript
详解堆的javascript实现方法
2016/11/29 Javascript
nodejs基础知识
2017/02/03 NodeJs
利用jQuery实现一个简单的表格上下翻页效果
2017/03/14 Javascript
详解vue-router基本使用
2017/04/18 Javascript
基于 webpack2 实现的多入口项目脚手架详解
2017/06/26 Javascript
JavaScript代码实现txt文件的上传预览功能
2018/03/27 Javascript
基于vue实现一个禅道主页拖拽效果
2019/05/27 Javascript
vue项目或网页上实现文字转换成语音播放功能
2020/06/09 Javascript
从零学Python之hello world
2014/05/21 Python
浅析Python中的多进程与多线程的使用
2015/04/07 Python
使用Python的urllib和urllib2模块制作爬虫的实例教程
2016/01/20 Python
深入解答关于Python的11道基本面试题
2017/04/01 Python
浅谈python中的__init__、__new__和__call__方法
2017/07/18 Python
django输出html内容的实例
2018/05/27 Python
Python selenium文件上传下载功能代码实例
2020/04/13 Python
Python reduce函数作用及实例解析
2020/05/08 Python
python GUI模拟实现计算器
2020/06/22 Python
Python关于拓扑排序知识点讲解
2021/01/04 Python
canvas之万花筒效果的简单实现(推荐)
2016/08/16 HTML / CSS
用CSS3实现无限循环的无缝滚动的实例代码
2017/07/04 HTML / CSS
Html5内唤醒百度、高德APP的实现示例
2019/05/20 HTML / CSS
澳大利亚最受欢迎的美发用品目的地:AMR
2019/08/28 全球购物
视图的作用
2014/12/19 面试题
万户网络JAVA程序员岗位招聘笔试试卷
2013/01/08 面试题
最新教师自我评价分享
2013/11/12 职场文书
大专生简历的自我评价
2013/11/26 职场文书
餐厅服务员岗位职责
2015/02/09 职场文书
2016同学毕业寄语大全
2015/12/04 职场文书