>  기사  >  웹 프론트엔드  >  스크립트를 사용하지 않고 js 파일을 가져오는 여러 가지 방법

스크립트를 사용하지 않고 js 파일을 가져오는 여러 가지 방법

高洛峰
高洛峰원래의
2016-12-08 14:50:481641검색

방법 1: Native

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>

방법 2: 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>

방법 3: require.js

require.js는 버전 2.1.1을 공유하므로 경우에 따라 jquery를 사용할 수 있습니다.

index.html

2e7409efecb0c40febdba6b3a8cbe4852cacc6d41bbb37262a98f745aa00fbf0

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으로 문의하세요.