关键字: javascript import, javascript include
现在常用的一种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; //原帖是这个...本人测试这行..无效 必须用text属性赋值
- script.defer=true; script.type='text/javascript';script.language='javascript';//本人测试修正..添加
script.text=js_content;//本人测试修正..添加//zfrong 09.5.20 - 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,add_script
- add_scripts(['test1.js', 'test2.js']), function(){
- //代码主体
- });
add_scripts方法使用了xmlhttp来读入js内容,并把读入的内容的写到一个新的script标签内,读入是异步执行的,当执行完毕后,会调用callback、