gpt4 book ai didi

javascript - .ready() 在 window.beforeunload 之后触发

转载 作者:行者123 更新时间:2023-11-29 15:05:06 26 4
gpt4 key购买 nike

我们有几个地方包含内联 <script>运行代码的 block ,由 $(document).ready() 包裹.其中几个 block 使用依赖于其他外部脚本的方法。在正常的页面执行过程中,这种技术工作正常,但是当用户在页面完全加载之前离开页面时,$(document).ready()事件被触发,IE 抛出这些错误:

"Object does not support this property or method"

通过一些测试,我发现 window.beforeunload事件在任何 ready 之前触发事件,所以我希望能够阻止 ready事件在那时被触发。理想情况下,我希望有一个通用的解决方案,这样我就不必修改所有内联代码。

如果这不可能,您是否建议将所有内联代码包装在 try-catch 中? block ,在执行内联代码之前确定是否已加载所有外部脚本等?

最佳答案

如果插件是在事后加载的,那么内联脚本不应该像那样贯穿始终。

IMO,更好的方法是像这样设置您的页面:

<html>
<head>
<title></title>
</head>
<body>
<div id="content">
</div>
<script src="jquery.js"></script>
<script src="jquery.customerPlugins.js"></script>
<script>
$(function(){
// all inline would go here!
});
</script>
<script src="main.js"></script>
</body>
</html>

但如果这不是一个选项,您可以(但可能不应该)(下面未经测试的代码):

<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script>
var readyQueue = [];
</script>
</head>
<body>
<script>
readyQueue.push(function(){
$("body").append("<div />").customPlugin();
});
</script>
<div id="content">
<script>
readyQueue.push(function(){
$("#content").customPlugin();
});
</script>
</div>
<script src="jquery.customPlugins.js"></script>
<script>
// do something like this...
$(function(){
var fn;
while(fn = readyQueue.shift()){
fn();
}
// if you want to continue to use readyQueue in code
// below/after this you could do something like the following:
readyQueue = {"push": function(fn){
fn();
})};
// this would execute immediately:
readyQueue.push(function(){
alert('Hello');
});
});
</script>
<script src="main.js"></script>
</body>
</html>

当你在做的时候,看看html5boilerplate.com .

关于javascript - .ready() 在 window.beforeunload 之后触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3915384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com