Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 276
Alon_T Avatar asked Aug 26 '12 12:08

Alon_T


People also ask

Can I use try-catch inside try-catch?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Can we use catch without try in JavaScript?

FYI: JavaScript allows for try-finally blocks (without catch ).

What is try-catch in JavaScript?

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.


1 Answers

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

like image 158
Paul S. Avatar answered Oct 05 '22 20:10

Paul S.