動態載入JS檔案的三種javascript方法
動態載入JS檔案的三種javascript方法
資料來源: https://www.itread01.com/p/1088079.html
方案01
function loadJs(file) { var head = $("head").remove("script[role='reload']"); $("<scri" + "pt>" + "</scr" + "ipt>").attr({ role: 'reload', src: file, type: 'text/javascript' }).appendTo(head); }
方案02
function reloadAbleJSFn(id,newJS) { var oldjs = null; var t = null; var oldjs = document.getElementById(id); if(oldjs) oldjs.parentNode.removeChild(oldjs); var scriptObj = document.createElement("script"); scriptObj.src = newJS; scriptObj.type = "text/javascript"; scriptObj.id = id; document.getElementsByTagName("head")[0].appendChild(scriptObj); }
方案03
<html> <head> <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裡面的,當點選click後執行這個函式 }); }); }); </script> </head> <body> <button type="button" id="loadButton">Load</button> <body> <html>
One thought on “動態載入JS檔案的三種javascript方法”
動態加載 (JAVASCRIPT)JS