English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

script를 사용하지 않고 js 파일을 도입하는 몇 가지 방법

메서드 하나: 원시

 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()
{
$('#loadButton').click(function(){
$.getScript('new.js',function(){
newFun('"Checking new script"');//이 함수는 new.js 내에 있으며, 클릭 시 실행됩니다.
});
});
});
</script> 
</head> 
<body> 
<button type="button" id="loadButton">Load</button>
 

제3법: require.js

require.js 공유2.1.1버전, 대형 프로젝트에 사용할 때 주의하세요. 일반적으로 jQuery를 사용하면 됩니다.

index.html

<!--엔트리 파일 main을 설정할 수 있습니다. js는 생략할 수 있습니다.-->
<script data-main="main" src="require.js"></script>

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 파일이 전역 범위를 공유하고, 범위 내에서 변수명, 메서드명이 덮어 써질 수 있습니다.

좋아하는 것