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?
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
FYI: JavaScript allows for try-finally blocks (without catch ).
JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With