stackoverflow如何知道javascript何时不起作用,并且能够在页面顶部通知用户?
是否可以判断脚本是否未加载或产生错误,然后仍能使用javascript生成错误消息?
答案 0 :(得分:2)
<noscript>
使用<noscript>
标记:
<noscript>
<div>JavaScript isn't available.<div>
<div>Please Enable it to continue.<div>
</noscript>
Stack Overflow使用以下代码:
<noscript>
<div id="noscript-warning">Stack Overflow works best with JavaScript enabled<img src="http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif" alt="" class="dno"></div>
</noscript>
try..catch
要处理错误,您可以将所有JS包装在函数中:
try {
runAllJavaScript();
} catch (e) {
alert("There was a fatal error :(");
}
eval
可以使用:
var code = new XMLHttpRequest();
code.onload = function () {
try { eval(code.responseText); }
catch (e) {
alert("The JavaScript had an error");
}
};
code.onerror = function () {
alert("Script didn't load!");
};
code.open("GET", "path/to/script.js");
code.send();
大多数人会不喜欢这个解决方案,因为它可以被认为是&#34; hacky&#34;
答案 1 :(得分:2)
<noscript>
<div id="noscript-warning">Stack Overflow works best with JavaScript enabled<img src="http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif" alt="" class="dno"></div>
</noscript>
JS加载问题只有在你可以加载JS时才会发生,这意味着启用了JS。确定JS是否已加载的最简单方法是挂钩加载成功/失败事件,或查询已知的内容在加载的JS中实现(在加载过程完成后)。