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
3 Answers
Reset to default 5You 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
版权声明:本文标题:Import a JavaScript file in HTML file inside of try-catch block - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744261921a2597757.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论