Javascript 如何测试document.write()是否成功
我在我的应用程序中包含了一些第三方代码,我看到它使用了document.write()代码,该代码封装在try..catch语句中。 document.write()不返回任何内容,因此我想知道是否有一种方法可以测试document.write()是否成功,以便测试捕获错误。 例如,我尝试将此脚本异步包含在内,但这停止了document.write()部分的执行,但它没有运行catch()部分中的代码 示例代码:Javascript 如何测试document.write()是否成功,javascript,Javascript,我在我的应用程序中包含了一些第三方代码,我看到它使用了document.write()代码,该代码封装在try..catch语句中。 document.write()不返回任何内容,因此我想知道是否有一种方法可以测试document.write()是否成功,以便测试捕获错误。 例如,我尝试将此脚本异步包含在内,但这停止了document.write()部分的执行,但它没有运行catch()部分中的代码 示例代码: try { document.write('<script type=
try {
document.write('<script type="text/javascript" src="/plugin.js">');
console.log('OK');
} catch (e) {
console.log('ERROR');
}
试试看{
文件。写(“”);
console.log('OK');
}捕获(e){
console.log('ERROR');
}
您可以在plugin.js中添加一个临时变量,或者简单地记录一个现有变量,然后在控制台中键入该变量。如果它存在,它将打印其值,否则它将打印“未定义”-是否有任何迹象表明它没有工作?您可以将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(“”);
if(document.getElementById('myscript')){
console.info(“成功”);
}否则{
控制台错误(“失败”);
}
或者,如果您不想更改任何内容,也可以尝试在第页的所有脚本中找到它:
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');
}
}());
document.write(“”);
(功能(){
var scripts=document.getElementsByTagName('script'),
l=scripts.length-1;
//如果您在document.write之后检查它,那么它应该是最后一个脚本
//在另一种情况下,您需要检查所有脚本。
//从src我正在删除域-至少Safari在这里返回完整的URL
如果(scripts.length&&scripts[l-1].src&&scripts[l-1].src.replace(/^([a-z]+:\/\/[^\/]*))/i',=='/plugin.js'){
console.info(“成功”);
}否则{
控制台错误(“失败”);
}
}());
谢谢,虽然理想情况下id喜欢不添加额外标记的解决方案,但它似乎工作得很好。通常,您可以将该id直接添加到脚本标记中,以不添加测试节点,甚至可以检查其父节点是否包含脚本,或者以其他方式找到它。是的,脚本上的id attr是一个更整洁的解决方案。您知道是否有任何条件会导致document.write引发异常,或者try-catch没有意义吗?