Import a JavaScript file in HTML file inside of try-catch block

html, javascript, try-catch

Solution

You can listen for an error (see this)

// make a script
var s = document.createElement('script');
// set it up
s.setAttribute('src',"file.js");
s.setAttribute('type',"text/javascript");
s.setAttribute('charset',"utf-8");
s.addEventListener('error', errorfunction, false);
// add to DOM
document.head.appendChild(s);

then in `errorfunction`, find out what happened & try to fix it as you would in a `catch`

Problem

I have a HTML page into which I want to import a JS file as follow: ``` <script src="file.js" type="text/javascript" charset="utf-8"></script> ``` But in case this file fails to run its scripts, the whole page obviously gets stuck. Can I import that file inside of a try-catch block?

Original source