如何测试document.write()是否成功

时间:2013-02-05 11:00:41

标签: javascript

我在我的应用程序中包含了一些第三方代码,我发现它使用了包含在try..catch语句中的document.write()代码。 document.write()没有返回任何内容,所以我想知道有没有办法测试document.write()是否成功,所以我可以测试捕获错误。 作为一个例子,我尝试包含这个脚本异步,但这停止了document.write()部分执行,但它没有运行catch()部分中的代码。

示例代码:

try {
   document.write('<script type="text/javascript" src="/plugin.js">');
   console.log('OK');
} catch (e) {
   console.log('ERROR');
}

2 个答案:

答案 0 :(得分:3)

您可以在脚本标记中添加id,然后通过id:

从DOM中获取它
document.write('<script type="text/javascript" src="/plugin.js" id="myscript"></script>');
if (document.getElementById('myscript')) {
    console.info('success');
} else {
    console.error('failure');
}

或者如果您不想更改任何内容,可以尝试在页面上的所有脚本中找到它:

document.write('<script type="text/javascript" src="/plugin.js"></script>');
(function () {
    var scripts = document.getElementsByTagName('script'),
        l = scripts.length - 1;
    // If you'll check that just after document.write then it should be last script
    // in the other case you would need to check all scripts.
    // From src I'm removing domain - at least Safari is returning full URL here
    if (scripts.length && scripts[l - 1].src && scripts[l - 1].src.replace(/^([a-z]+:\/\/[^\/]*)/i, '') == '/plugin.js') {
        console.info('success');
    } else {
        console.error('failure');
    }
}());

答案 1 :(得分:0)

你可以在plugin.js中添加一个临时变量,或者只是记下一个现有变量,然后在控制台中输入这个变量。如果它存在,它将打印其值,否则它将打印'undefined' - 是否有任何迹象表明它没有工作?