多个 $(document).ready(function(){})

发布于 2024-11-08 03:48:35 字数 311 浏览 4 评论 0原文

我最近开始使用 jQuery 工作,现在当我正在开发一个项目时,我使用 ajax 函数并一次又一次加载相同的库(我已经编写)。由于 $(document).ready(function(){}) 一次又一次地调用。意味着如果我一次又一次地加载 4 次,一个函数会调用 4 次。

我想清理/未准备/卸载以前准备好的功能,并想准备好新功能。我也经常尝试 $(function(){}) 。但结果相同。我试图获取任何相应/相关的主题。但无法找到。

如果我找不到这个或没有人可以帮助我。那么我想我应该将我的一个库拆分/分解为多个库。

I have recently started working in jQuery and now when i am working on an project where i am using ajax function and loading the same library(i have written) again and again. and due to that $(document).ready(function(){}) calls again and again. Means one function calls for 4 time if i use to load it 4 times again and again.

I want to clean/unready/unload previous ready function and want to ready new function . i use to try on $(function(){}) also. but the same result. i tried to get any respective/ related topic. but couldn't find out.

If i could not find this or no one can help me. then i think i should have to split/break my one library to numbers of libraries.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一个人的旅程 2024-11-15 03:48:35

这按预期工作,多个事件注册将彼此独立地触发。

不过,您可以采取解决方法:设置一个标志,如果多次调用,该标志将阻止执行。例如,此页面将加载您的脚本四次,但事件注册只会发生一次:

this is your HTML page
<script>
  var alreadyRan = false;
</script>
<script src="yourscript.js?firstload"></script>
<script src="yourscript.js?secondload"></script>
<script src="yourscript.js?thirdload"></script>
<script src="yourscript.js?nextload"></script>
etc.

然后,在 yourscript.js 中:

if (!alreadyRan) { // we declared alreadyRan in the global scope
  alreadyRan = true; // won't run on further invocations
  // thus the handler will only be registered one time
  $(document).ready(function(){
    // your onready code
  });
}

请注意,将您的库拆分为只需要一次的部分和将其拆分为需要的部分可能会更容易被重复调用,并且只加载初始部分一次。

That works as intended, multiple event registrations will fire independently of each other.

You could make a workaround, though: set a flag that will prevent execution if called more than once. For example, this page would load your script four times, but the event registration would only happen once:

this is your HTML page
<script>
  var alreadyRan = false;
</script>
<script src="yourscript.js?firstload"></script>
<script src="yourscript.js?secondload"></script>
<script src="yourscript.js?thirdload"></script>
<script src="yourscript.js?nextload"></script>
etc.

Then, in yourscript.js:

if (!alreadyRan) { // we declared alreadyRan in the global scope
  alreadyRan = true; // won't run on further invocations
  // thus the handler will only be registered one time
  $(document).ready(function(){
    // your onready code
  });
}

Note that it might be easier to split your library into the part that is only needed once and into the part that is called repeatedly, and only load that initial part once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文