眼眸繁星
2019-07-02 16:10:51
在JS內(nèi)動態(tài)加載JS我有一個動態(tài)網(wǎng)頁,需要導(dǎo)入外部JS文件(在IF條件)在另一個javascript文件中。我試圖尋找一個可行的解決方案,但沒有奏效。我嘗試使用以下方法將JS文件加載到DOM中document.createElement()但也沒用。顯然,Js被加載到DOM中,但在當(dāng)前的JS文件中無法訪問。jquery中的解決方案也很好。
3 回答

斯蒂芬大帝
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊
$.getScript()
jQuery.loadScript = function (url, callback) { jQuery.ajax({ url: url, dataType: 'script', success: callback, async: true });}
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){ //Stuff to do after someScript has loaded});

繁星點(diǎn)點(diǎn)滴滴
TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個贊
var script = document.createElement('script');script.src = something;//do stuff with the script
load
var script = document.createElement('script');script.onload = function () { //do stuff with the script};script.src = something;document.head.appendChild(script); //or something of the likes

慕村9548890
TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個贊
var loadJS = function(url, implementationCode, location){ //url is URL of external file, implementationCode is the code //to be called from the file, location is the location to //insert the <script> element var scriptTag = document.createElement('script'); scriptTag.src = url; scriptTag.onload = implementationCode; scriptTag.onreadystatechange = implementationCode; location.appendChild(scriptTag);};var yourCodeToBeCalled = function() {//your code goes here}loadJS('yourcode.js', yourCodeToBeCalled, document.body);
添加回答
舉報
0/150
提交
取消