首页 > 网站 > WEB开发 > 正文

动态加载javascript增强版

2024-04-27 14:21:44
字体:
来源:转载
供稿:网友

动态加载javascript增强版

我们经常使用动态加载Javascript,写个函数很容易现实,之前也写过一个函数,不过当加载多个JS时,只能根据浏览器返回的顺序来先后加载,这肯定不是我们想要的,现在使用了一下技巧,当加载多个JS时,能按照我们的顺序加载:

Js代码 复制代码收藏代码
  1. /*
  2. Name:动态加载JS
  3. Author:kingwellLeng
  4. Date:2013/4/21
  5. E-mail:jinhua.leng##Gmail.com
  6. */
  7. functiongetScript(obj,callback){
  8. vararr=obj,
  9. timeout,
  10. str=typeofobj==='string';
  11. functionadd(){
  12. varscript=document.createElement("script");
  13. header=document.getElementsByTagName("head")[0];
  14. script.src=str?obj:arr[0];
  15. script.type="text/javascript";
  16. if(str){
  17. if(script.readyState){
  18. script.onreadystatechange=function(){
  19. if(script.readyState==='loaded'||script.readyState==='complete'){
  20. script.onreadystatechange=null;
  21. callback&&callback();
  22. }
  23. };
  24. }else{
  25. script.onload=function(){
  26. callback&&callback();
  27. };
  28. }
  29. }else{
  30. if(arr.length>=1){
  31. if(script.readyState){
  32. script.onreadystatechange=function(){
  33. if(script.readyState==='loaded'||script.readyState==='complete'){
  34. script.onreadystatechange=null;
  35. arr.shift();
  36. timeout=setTimeout(add,1);
  37. }
  38. };
  39. }else{
  40. script.onload=function(){
  41. arr.shift();
  42. timeout=setTimeout(add,1);
  43. };
  44. }
  45. }else{
  46. clearTimeout(timeout);
  47. callback&&callback();
  48. }
  49. }
  50. header.appendChild(script);
  51. }
  52. add();
  53. }
/*    Name:动态加载JS    Author:kingwell Leng    Date : 2013/4/21    E-mail: jinhua.leng##gmail.com*/function getScript(obj, callback) {var arr = obj,timeout,str = typeof obj === 'string';function add() {var script = document.createElement("script");header = document.getElementsByTagName("head")[0];script.src = str ? obj : arr[0];script.type = "text/javascript";if (str) {if (script.readyState) {script.onreadystatechange = function () {if (script.readyState === 'loaded' || script.readyState === 'complete') {script.onreadystatechange = null;callback && callback();}};} else {script.onload = function () {callback && callback();};}} else {if (arr.length >= 1) {if (script.readyState) {script.onreadystatechange = function () {if (script.readyState === 'loaded' || script.readyState === 'complete') {script.onreadystatechange = null;arr.shift();timeout = setTimeout(add, 1);}};} else {script.onload = function () {arr.shift();timeout = setTimeout(add, 1);};}} else {clearTimeout(timeout);callback && callback();}}header.appendChild(script);}add();}

调用:

Js代码 复制代码收藏代码
  1. getScript(['http://code.jquery.com/jquery-1.9.1.min.js','js1.js','js2.js','js3.js','js4.js'],function(){
  2. alert('我是按顺序加载啦');
  3. });
getScript(['http://code.jquery.com/jquery-1.9.1.min.js','js1.js', 'js2.js', 'js3.js', 'js4.js'], function () {alert('我是按顺序加载啦');});

现在是按照我们写代码的顺序加载啦...


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表