亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在JS內動態加載JS

在JS內動態加載JS

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

3 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

jQuery$.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});


查看完整回答
反對 回復 2019-07-02
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

我的猜測是,在只使用DOM的解決方案中,您所做的事情如下:

var script = document.createElement('script');script.src = something;//do stuff with the script

首先,因為腳本沒有添加到文檔樹中,所以不會被加載,所以這是行不通的。此外,即使您這樣做,在加載其他腳本時,javascript的執行仍在繼續,因此在完全加載該腳本之前,它的內容是不可用的。

你可以聽劇本的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


查看完整回答
反對 回復 2019-07-02
?
慕村9548890

TA貢獻1884條經驗 獲得超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);

有關更多信息,請參見本網站如何在另一個JavaScript文件中包含JavaScript文件?,這是我的功能理念的來源。


查看完整回答
反對 回復 2019-07-02
  • 3 回答
  • 0 關注
  • 477 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號