How to detect script: // URL error loading in Firefox?

I want to determine if the script tag is loaded (which was dynamically created and added to the DOM). The onerror event fires, with the exception of files: // URL in Firefox.

Unfortunately, none of the methods described here (with the exception of timeouts, which are unacceptable in my case) seem to work in Firefox if the src tag of the script file is: // URL (or the relative URL and page were loaded through the file: // url)

Test case:

var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', 'doesnotexist.js'); script.onerror = function() { alert("Loading failed!"); } document.getElementsByTagName('head')[0].appendChild(script); 

Upload this to the HTML page with the file: // URL. The onerror event will not be fired in Firefox. Download from a web server or in Safari or Chrome and it will.

This seems like a mistake to me. Is there any known way around it?

+6
javascript firefox
source share
2 answers

What to do if you used the Pauls solution to get the document, but ignored the result. If it loads, create a script tag. The disadvantage is that the file will be downloaded twice.

+1
source share
 var loadScript = function(scriptURL, failureCallback) { var script = document.createElement('script'), scriptProtocol = scriptURL.match(/^([a-zA-Z]+:)\/\//); script.setAttribute('type', 'text/javascript'); if (navigator.product === 'Gecko' && navigator.userAgent.indexOf('KHTML') === -1 && window.location.protocol === 'file:' && (!scriptProtocol || scriptProtocol[1] === 'file:')) { var req = new XMLHttpRequest(); req.open('GET', scriptURL, true); req.onreadystatechange = function () { if (req.readyState === 4) { if (req.status === 0) script.textContent = req.responseText; else failureCallback(); } }; try { req.send(null); } catch (e) { failureCallback(); } } else { script.setAttribute('src', scriptURL); script.onerror = failureCallback; } document.getElementsByTagName('head')[0].appendChild(script); }; loadScript('doesnotexist.js', function() { alert('Loading failed!'); }); 

A bit of a hack, but it seems to work.

+2
source share

All Articles