加载外部javascript文档后执行javascript

时间:2009-11-23 21:43:35

标签: javascript dom

我想包含一个远程js文件,然后在完成执行后调用一个函数。我以为我可以这样做:

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

事实证明,警报('测试')会被文件中的任何内容消灭。反正有吗?

6 个答案:

答案 0 :(得分:3)

此函数将从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);

}

答案 1 :(得分:2)

首先,忘记在同一个脚本标签上使用src和内部内容。尽管John Resig在blog post中对此进行了一些思考,但它并没有以任何一般方式起作用。

第二件事是,决定是要同步加载脚本 还是异步。如果脚本很大或者长时间运行,你要么想要异步执行,要么在页面底部同步执行它,以免阻止渲染。

您的方法(动态附加脚本标记)将异步加载和运行它,这意味着应该在完成后运行的代码需要进入在脚本完成时触发的回调。设置它并不是很简单,所以我建议使用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的怪癖。

答案 2 :(得分:1)

添加另一个

<script></script> 
第一个应该工作之后的

部分。 AFAIK你不能在一个标签中混合使用外部和内联JS。

但是我不确定将代码放入“innerHTML”是否会按预期工作。我很想知道是否这样做。

答案 3 :(得分:1)

您是否尝试过创建第二个包含您要运行的代码的脚本元素,并在添加了需要下载的代码后添加该元素?

答案 4 :(得分:0)

您可以使用sc load事件来确定该脚本何时加载然后执行某些操作。

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

答案 5 :(得分:0)

我昨天为自己创建了这个脚本。它使用jQuery通过AJAX加载JavaScript文件,并将它们添加到标题的脚本标记中,然后调用我传递的回调函数。

对我来说一直很好。

/**
 * 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]);
            }
        });
    }
}