How to test if document.write() was successful
I'm including some 3rd party code in my application and I see that it uses document.write() code which is wrapped in a try..catch statement. The document.write() doesn't return anything, so I wanted to know is there a way to test if document.write() was successful, so I can test catching the error. As an example, I tried including this script async but this stopped the document.write() part executing but it didnt run the code in the catch() part.
example code:
try {
document.write('<script type="text/javascript" src="/plugin.js">');
console.log('OK');
} catch (e) {
console.log('ERROR');
}
You can add id to script tag and then fetch it from DOM by id:
document.write('<script type="text/javascript" src="/plugin.js" id="myscript"></script>');
if (document.getElementById('myscript')) {
console.info('success');
} else {
console.error('failure');
}
or you can try to find it in all scripts on page if you don't want to change anything:
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');
}
}());
You could add a temporary variable, or simply take note of an existing one, inside plugin.js, then afterwards type this variable into the console. If it exists, it'll print its value, else it'll print 'undefined' - is there any indication that it hasn't worked?
链接地址: http://www.djcxy.com/p/47906.html