如何在html和JS中包含Javascript JS文件终极解决方案

关键字: javascript import, javascript include

现在常用的一种javascript的方法是在当前的html文档中插入一个script标签,在标签中引入script脚本

 

Js代码
  1. var __includes__ = new Array;    
  2. Array.prototype.indexOf = function(obj){ for(var i = 0; i < this.length; i++){if (this[i] == obj)return i;}return -1;}  
  3.         Array.prototype.add = function(obj){this[this.length] = obj;}  
  4. function include_js(js)  
  5. {  
  6.     if (__includes__.indexOf(js) > -1)return;  
  7.     __includes__.add(js);  
  8.     var head = document.getElementsByTagName('head')[0];      
  9.     script = document.createElement('script');  
  10.     script.src = js;  
  11.     script.type = 'text/javascript';  
  12.     head.appendChild(script);  
  13. }  

 

当你只是在你的htmlw文档中使用这个方法的时候,一切OK,这其实是script的标签的一种快捷的写法而已。

但是,如果你在一个javascript使用这个方法,问题就来了,比如

我在test.js中使用include_js("test1.js"),在test1.js中有一个变量test1是在test.js中要使用 的,在webkit中尽然出现了test1变量未定义的错误,我不知道ie和firefox是否有这种问题,我想可能是include_js本身不是同步 执行导致的,所以我只好使用以下方法来完善inlcude_js

 

 

 

Js代码
  1. var __includes__ = new Array;    
  2. Array.prototype.indexOf = function(obj){ for(var i = 0; i < this.length; i++){if (this[i] == obj)return i;}return -1;}  
  3.         Array.prototype.add = function(obj){this[this.length] = obj;}  
  4.           
  5. function xhttp(url, callback)  
  6. {  
  7.     var request = null;  
  8.     if (typeof XMLHttpRequest != 'undefined') {  
  9.         request = new XMLHttpRequest();  
  10.     }  
  11.     else if (typeof ActiveXObject != 'undefined') {  
  12.         request = new ActiveXObject('Microsoft.XMLHTTP');  
  13.     }  
  14.     request.open('GET', url, true);  
  15.     request.onreadystatechange = function () {  
  16.         if (request.readyState == 4) {  
  17.             callback(request.responseText);  
  18.         }  
  19.     };  
  20.     request.send(null);           
  21. }  
  22. function add_scripts(jss, callback)  
  23. {  
  24.     var func = function( jss, idx, callback){  
  25.         if (idx == jss.length) {callback();return};  
  26.         add_script(jss[idx], function(){func(jss, ++idx, callback);});  
  27.     }  
  28.     func(jss, 0, callback);  
  29. }  
  30. function add_script(js, callback)  
  31. {  
  32.     if (__includes__.indexOf(js) > -1){callback();return;}  
  33.     __includes__.add(js);      
  34.     xhttp(js, function(js_content){  
  35.         var head = document.getElementsByTagName('head')[0];      
  36.         script = document.createElement('script');  
  37.         head.appendChild(script);  
  38.        // script.innerHTML = js_content;  //原帖是这个...本人测试这行..无效 必须用text属性赋值
  39. script.defer=true; script.type='text/javascript';script.language='javascript';//本人测试修正..添加
                script.text=js_content;//本人测试修正..添加//zfrong 09.5.20
  40.         callback();  
  41.     });  
  42. }  
  43.           
  44.         function include_js(js)  
  45.         {  
  46.             if (__includes__.indexOf(js) > -1)return;  
  47.             __includes__.add(js);  
  48.             var head = document.getElementsByTagName('head')[0];      
  49.             script = document.createElement('script');  
  50.             script.src = js;  
  51.             script.type = 'text/javascript';  
  52.             head.appendChild(script);  
  53.         }     

 

 当我在html文档中引入的时候,我用 include_js,当我在js文件中引入js时候,我使用add_scripts,add_script

 

Js代码
  1. add_scripts(['test1.js''test2.js']), function(){  
  2. //代码主体  
  3.   
  4. });  

 

 add_scripts方法使用了xmlhttp来读入js内容,并把读入的内容的写到一个新的script标签内,读入是异步执行的,当执行完毕后,会调用callback、

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 什么是promise? Promise是一种异步编程的解决方案,它是ES6新增的特性,用于解决回调地狱的问题。Promise代表一个异步操作的最终完成状态(成功或失败)以及返回的结果值。 2. 怎么使用promise? 使用Promise需要以下几个步骤: (1)创建Promise对象,将异步任务封装在Promise对象。 (2)使用then方法处理成功状态的结果。 (3)使用catch方法处理失败状态的结果。 例如: ```javascript let promise = new Promise(function(resolve, reject) { setTimeout(() => { if (Math.random() < 0.5) { resolve('success'); } else { reject('fail'); } }, 1000); }); promise.then(function(result) { console.log(result); // 'success' }).catch(function(error) { console.log(error); // 'fail' }); ``` 3. 怎么手写promise? 手写Promise需要实现以下几个步骤: (1)创建Promise类,定义构造函数,初始化Promise状态。 (2)定义resolve方法和reject方法,分别用于改变Promise状态为成功和失败。 (3)定义then方法和catch方法,分别用于处理成功状态和失败状态。 (4)实现链式调用,即then方法可以无限调用。 例如: ```javascript class MyPromise { constructor(executor) { this.status = 'pending'; this.value = undefined; this.reason = undefined; let resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled'; this.value = value; } }; let reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected'; this.reason = reason; } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { if (this.status === 'fulfilled') { onFulfilled(this.value); } else if (this.status === 'rejected') { onRejected(this.reason); } return this; } catch(onRejected) { if (this.status === 'rejected') { onRejected(this.reason); } return this; } } ``` 使用手写的Promise: ```javascript let promise = new MyPromise(function(resolve, reject) { setTimeout(() => { if (Math.random() < 0.5) { resolve('success'); } else { reject('fail'); } }, 1000); }); promise.then(function(result) { console.log(result); // 'success' }).catch(function(error) { console.log(error); // 'fail' }); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值