简体   繁体   English

在 try-catch 块内的 HTML 文件中导入 JavaScript 文件

[英]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:我有一个 HTML 页面,我想在其中导入一个 JS 文件,如下所示:

<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?我可以在 try-catch 块中导入该文件吗?

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然后在errorfunction ,找出发生了什么并尝试像在catch一样修复它

You can use AJAX .您可以使用AJAX This assumes you have jQuery , but you can easily avoid using it ( here you can find one of many tutorials).这假设您有jQuery ,但您可以轻松避免使用它(在这里您可以找到许多教程之一)。 Here's 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 that helped in any manner!希望以任何方式帮助!

您可以尝试类似的操作或创建 JS 元素并在此元素内设置 src

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM