admin管理员组

文章数量:1405170

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?

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?

Share Improve this question edited May 22, 2020 at 22:41 rob006 22.2k5 gold badges57 silver badges77 bronze badges asked Aug 26, 2012 at 12:58 Alon_TAlon_T 1,4405 gold badges28 silver badges48 bronze badges 2
  • Fixed your formatting - you might want to check that what I fixed it to is what you're actually doing. – Eric Commented Aug 26, 2012 at 13:24
  • Where is it imported? In the head? Try moving it in front of the closing body tag. – DanMan Commented Aug 26, 2012 at 13:35
Add a ment  | 

3 Answers 3

Reset to default 5

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

You can use AJAX. This assumes you have jQuery, but you can easily avoid using it (here you can find one of many tutorials). Here's an example:

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

Hope that helped in any manner!

You can try something like that or create JS element and set src inside this element

document.write("<script src=\"file.js\" type=\"text/javascript\" charset=\"utf-8\"></script>");

本文标签: Import a JavaScript file in HTML file inside of trycatch blockStack Overflow