龙空技术网

5种动态加载js脚本的方式

程序员苏小胖 52

前言:

而今你们对“jquery如何加载js文件”大致比较关切,各位老铁们都需要知道一些“jquery如何加载js文件”的相关知识。那么小编也在网摘上汇集了一些对于“jquery如何加载js文件””的相关知识,希望朋友们能喜欢,各位老铁们一起来了解一下吧!

方式一、原生js最简单方式

(function () {    var li = document.createElement('script');     li.type = 'text/javascript';     li.src = ";;     li.async = true;     var s = document.getElementsByTagName('script')[0];     s.parentNode.insertBefore(li, s);})();
方式二、原生js
// Load a JavaScript file from other JavaScript filefunction loadScript(urlPack, callback) {    var url = urlPack.shift();    var subCallback;    if (urlPack.length == 0) subCallback = callback;    else subCallback = function () {        console.log("Log script: " + new Date().getTime());        loadScript(urlPack, callback);    }    // Adding the script tag to the head as suggested before    var head = document.getElementsByTagName('head')[0];    var script = document.createElement('script');    script.type = 'text/javascript';    script.src = url;    // Then bind the event to the callback function.    // There are several events for cross browser compatibility.    script.onreadystatechange = subCallback;    script.onload = subCallback;    // Fire the loading    head.appendChild(script);}

使用

loadScript([    "js/DataTable/jquery.dataTables.js",    "js/DataTable/dataTables.bootstrap.js",    "js/DataTable/dataTables.buttons.min.js",    "js/DataTable/dataTables.colReorder.min.js",    "js/DataTable/dataTables.fixedHeader.min.js",    "js/DataTable/buttons.bootstrap.min.js",    "js/DataTable/buttons.colVis.min.js",    "js/DataTable/buttons.html5.min.js"], function() {     // 干点啥});
方式三、ES6
function loadJs( url ){  return new Promise(( resolve, reject ) => {    if (document.querySelector( `head > script[ src = "${url}" ]`) !== null ){        console.warn( `script already loaded: ${url}` );        resolve();    }    const script = document.createElement( "script" );    script.src = url;    script.onload = resolve;    script.onerror = function( reason ){        // This can be useful for your error-handling code        reason.message = `error trying to load script ${url}`;        reject( reason );    };    document.head.appendChild( script );  });}
// USE1try { await loadJs(";); }catch(error) { console.log(error); }// USE2await loadJs( "; ).catch( err => {} );// USE3loadJs( "; ).then( res => {} ).catch( err => {} );
方式四、link

MyClass.js.html:

<script>   class MyClass {      // Your code here..   }</script>
<link rel="import" href="relative/path/to/MyClass.js.html"/><script>   var myClass = new MyClass();   // Your code here..</script>
方式五、jQuery
// jQuery$.getScript('/path/to/imported/script.js', function(){    // Script is now loaded and executed.    // Put your dependent JavaScript code here.});

标签: #jquery如何加载js文件 #调试动态加载的js #js加载方法 #jquery loadingjs