Import javascript file into html file inside try catch block

I have an html page into which I import js files, following

<script src="file.js" type="text/javascript" charset="utf-8"></script> 

but in case this file does not run its scripts, the whole page obviously gets stuck

Can I import this file into a catch try block?

thanks

+6
source share
2 answers

You can listen for the 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 the errorfunction , find out what happened and try to fix it, as in catch

+4
source

You can use AJAX . This suggests that you are jQuery , but you can easily avoid using it ( here you can find one of many tutorials). Here is an example:

 $.get("http://yoursite.com/file.js", function(data) { try { eval(data); //Run the JavaScript, which is equivalent to adding it } catch (err) { //handle errors } }); 

Hope this helped in any way!

-1
source

Source: https://habr.com/ru/post/923785/


All Articles