簡體   English   中英

加載外部javascript文檔后執行javascript

[英]Execute javascript after external javascript document has loaded

我想包含一個遠程js文件,然后在完成執行后調用一個函數。 我以為我可以做這樣的事情:

var sc = document.createElement('script');
sc.setAttribute('type', 'text/javascript');
sc.setAttribute('src', src);
sc.innerHTML = "alert('testing');"
parentNode.appendChild(sc);

事實證明,無論文件中有什么內容,都會刪除alert('testing')。 反正有這樣做嗎?

該函數將從scriptPath加載庫,並在加載腳本后執行傳遞的處理函數:

loadExternalScript : function(scriptPath, handler) {

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptPath;
    script.charset = 'utf-8';

    script.onload = handler;

    head.appendChild(script);

}

第一件事是,忘記在同一腳本標簽上使用src和內部內容。 盡管John Resig在此博客文章中對此進行了一些思考,但它不能以任何一般方式起作用。

第二件事是,決定要同步還是異步加載腳本。 如果腳本較大或運行時間較長,則可以異步執行,也可以在頁面底部同步執行,以免阻止渲染。

您的方法(動態添加腳本標簽)將異步加載和運行,這意味着在腳本完成后應運行的代碼需要進入一個在腳本完成時觸發的回調 設置起來不是很簡單,所以我建議要么使用jQuery及其ajax.getScript函數,要么直接從jQuery源中復制getScript功能(jQuery 1.3.2的3473-3505行)。

如果要避免所有這些,只需同步加載即可。 這是通過使用document.write完成的。 您提供的示例如下所示:

document.write("<scr" + "ipt src='" + src + "' type='text/javascript'></script>");
// The script is guaranteed to have executed at this point
alert('testing');

確保將“腳本”分割成這樣,我不確定為什么,但這是JavaScript的怪癖。

添加另一個

<script></script> 

第一個之后的部分應該可以工作。 AFAIK,您不能在一個標簽中混合使用外部和內聯JS。

但是我不確定是否將代碼放入“ innerHTML”中是否可以正常工作。 我有興趣看看是否可以。

您是否嘗試過創建包含要運行的代碼的第二個腳本元素,並在添加了需要下載的代碼之后添加它?

您可能可以使用sc load事件確定該腳本的加載時間,然后執行一些操作。

范例http://iamnoah.blogspot.com/2008/01/ie-script-load-event.html

我昨天為自己創建了此腳本。 它使用jQuery通過AJAX加載JavaScript文件,並將它們以script標記添加到標頭中,然后調用我傳遞的回調函數。

對我來說一直很好。

/**
 * Fetches and executes JavaScript files from the server.
 * @param files A list of files to load, or a single filename as a string.
 * @param callback The function to call when the process is done. Passes a boolean success value as the only parameter.
 * @param thisObject The calling object for the callback.
 */
window.include = function(files, callback, thisObject) {
    var current_location = null;
    var recursive = false;

    if(!(thisObject instanceof Object)) {
        thisObject = window;
    }

    if(files instanceof Array || files instanceof Object) {
        if(files.length > 0) {
            current_location = files.shift();
            recursive = true;
        }
        else {
            callback.apply(thisObject, [true]);
            return;
        }
    }
    else if(typeof files == 'string') {
        current_location = files;
    }
    else {
        callback.apply(thisObject, [false]);
        return;
    }

    if((current_location instanceof String || typeof current_location == 'string') && current_location != '')
    {
        $.ajax({
            type : 'GET',
            url  : current_location,
            timeout : 5000,
            success : function(data) {
                var scriptTag = $(document.createElement('script'));
                scriptTag.attr('type', 'text/javascript');
                scriptTag.html(data);
                $('head').append(scriptTag);

                if(recursive) {
                    window.adlib.include(files, callback, thisObject);
                }
                else {
                    callback.apply(thisObject, [true]);
                }
            },
            error : function() {
                callback.apply(thisObject, [false]);
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM