现在常用的一种javascript的方法是在当前的html文档中插入一个script标签,在标签中引入script脚本
var __includes__ = new Array;
Array.prototype.indexOf = function(obj){ for(var i = 0; i < this.length; i++){if (this[i] == obj)return i;}return -1;}
Array.prototype.add = function(obj){this[this.length] = obj;}
function include_js(js)
{
if (__includes__.indexOf(js) > -1)return;
__includes__.add(js);
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.src = js;
script.type = 'text/javascript';
head.appendChild(script);
}
当你只是在你的htmlw文档中使用这个方法的时候,一切OK,这其实是script的标签的一种快捷的写法而已。
但是,如果你在一个javascript使用这个方法,问题就来了,比如
我在test.js中使用include_js("test1.js"),在test1.js中有一个变量test1是在test.js中要使用的,在webkit中尽然出现了test1变量未定义的错误,我不知道ie和firefox是否有这种问题,我想可能是include_js本身不是同步执行导致的,所以我只好使用以下方法来完善inlcude_js
var __includes__ = new Array;
Array.prototype.indexOf = function(obj){ for(var i = 0; i < this.length; i++){if (this[i] == obj)return i;}return -1;}
Array.prototype.add = function(obj){this[this.length] = obj;}
function xhttp(url, callback)
{
var request = null;
if (typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
else if (typeof ActiveXObject != 'undefined') {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', url, true);
request.onreadystatechange = function () {
if (request.readyState == 4) {
callback(request.responseText);
}
};
request.send(null);
}
function add_scripts(jss, callback)
{
var func = function( jss, idx, callback){
if (idx == jss.length) {callback();return};
add_script(jss[idx], function(){func(jss, ++idx, callback);});
}
func(jss, 0, callback);
}
function add_script(js, callback)
{
if (__includes__.indexOf(js) > -1){callback();return;}
__includes__.add(js);
xhttp(js, function(js_content){
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
head.appendChild(script);
script.innerHTML = js_content;
callback();
});
}
function include_js(js)
{
if (__includes__.indexOf(js) > -1)return;
__includes__.add(js);
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.src = js;
script.type = 'text/javascript';
head.appendChild(script);
}
当我在html文档中引入的时候,我用 include_js,当我在js文件中引入js时候,我使用
add_scripts(['test1.js', 'test2.js']), function(){
//代码主体
});
add_scripts方法使用了xmlhttp来读入js内容,并把读入的内容的写到一个新的script标签内,读入是异步执行的,当执行完毕后,会调用callback、
import javascript in javascript
include javascript in javascript
本文介绍了一种在JavaScript中动态加载外部JS文件的方法。通过创建script标签并利用XMLHttpRequest获取脚本内容,确保脚本按需加载且能正确执行依赖项。适用于解决因异步加载导致的变量未定义等问题。

被折叠的 条评论
为什么被折叠?



