What are the side effects (if any) of multiple $(document).ready() in an HTML page?

痞子三分冷 提交于 2019-12-04 02:31:14
karim79

There are no problems with multiple $(document).ready() calls, only a couple of caveats:

  • Reduced readability.
  • Scope: a function/variable/object declared inside one $(document).ready() will not be visible in any others. See this simple demo.

Also see this previous question on SO:

You can indeed use as many instances of $(document).ready() on a page as you like. You can group your blocks of initialization code in whichever way makes the most sense for your application. What you gain in flexibility you may lose a bit in clarity, though, since it's no longer as easy to see what happens when onLoad fires.

References: jQuery Tutorial on Multiple $(document).ready()

If you want to reuse js code snippets on different pages, you can use the view.yml config file in each of your modules like this:

firstActionSuccess:
  javascripts: [js1.js, js2.js]
secondActionError:
  javascripts: [js1.js, js3.js]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!