My pages relies on this script currently:
script a)
<script src="https://mipage.com/pathtoscript/owlscript.js"></script>
Incase loading this (script a) ) fails, I'd want to load:
script b)
<script src="https://otherpage.com/pathtoscript/owlscript.js"></script>
Any way to do this ?
PS: I've seen implementations for jsquery, but those won't work here...
The best way for this is to listen for the error event of the first script tag. You can do this for example with the onerror property:
<script src="https://mipage.com/pathtoscript/owlscript.js" onerror="loadFallbackScript()"></script>
and then loading the fallback script from code:
function createScriptElement(src) {
const script = document.createElement('script');
script.src = src;
return script;
}
function loadFallbackScript() {
const fallbackScriptElement = createScriptElement('fallback.js');
document.head.append(fallbackScriptElement);
}
But since this requires loadFallbackScript to be a global function a cleaner way would be to create the first script tag dynamically as well and attach the event listener from code:
// execute this instead of the <script> tag in the html
const externalScriptElement = createScriptElement('external.js');
externalScriptElement.addEventListener('error', loadFallbackScript);
document.head.append(externalScriptElement);