Home > Web Front-end > JS Tutorial > body text

Several ways to import js files without using scripts

高洛峰
Release: 2016-12-08 14:50:48
Original
1682 people have browsed it

Method 1: Native

 adc.js content is as follows:

var hello = "H9";
Copy after login

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>
Copy after login

Method 2: jquery.js

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

<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>
Copy after login

Method 3 :require.js

require.js shares version 2.1.1. Note that it is for use in large projects. In this case, just use jquery.

index.html


main.js

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

Using requireJs can easily import js files, but you should pay attention to the problem of variable name and method name conflicts in js files. Cause: Browser js files share the global scope, and variable names and method names in the scope may be overwritten


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template