首页  >  文章  >  web前端  >  不使用script导入js文件的几种方法

不使用script导入js文件的几种方法

高洛峰
高洛峰原创
2016-12-08 14:50:481641浏览

方法一:原生

 adc.js内容如下:

var hello = "H9";

   

html.html

<script>
      var s = document.createElement("script");
      s.src = "abc.js";
      document.head.appendChild(s);
      s.addEventListener("load",function(){
        // 等待s的load事件加载完响应,防止未加载完就调用出错
        console.log(hello);
      })
 
      setTimeout(function(){//或者使用定时器保证其载入完后调用(不安全,不如监听事件好)
        console.log(hello);
      },1000);
     // $.getScript("abc.js");
  </script>

   

方法二:jquery.js

$.getScript("abc.js",function(){ alert("heheheh"); console.log(hello); });

    

<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(function()
{
$(&#39;#loadButton&#39;).click(function(){
$.getScript(&#39;new.js&#39;,function(){
newFun(&#39;"Checking new script"&#39;);//这个函数是在new.js里面的,当点击click后运行这个函数
});
});
});
</script>
</head>
<body>
<button type="button" id="loadButton">Load</button>

  

   

方法三:require.js

require.js分享2.1.1版本,注意是针对大项目使用,一边情况下使用jquery即可。

index.html

0bc67fd303503dec2126c02c98bcadae
7c5d0937109e9eb3185fd2857f3b05572cacc6d41bbb37262a98f745aa00fbf0

main.js

console.log("你好世界");
require(["js1","js2","js3"],function () {
  // 是异步加载导入。js后缀可以省略
  console.log("你们加载完了么?");
  var total = num1+num2+num3;
  console.log(total);
  hello1();
  hello2();
  hello3();
})

   

使用requireJs可以很方便的导入js文件,但是要注意js文件中变量名方法名冲突的问题。 产生原因:浏览器js文件共用全局作用域,作用域中变量名方法名可能被覆盖


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn