$.ready() before closing body

前端 未结 3 1949
终归单人心
终归单人心 2021-02-14 13:21

This is not a real coding question, more of a real-world statement.

I have previously noted that DOMReady events are slow, very slow. So, I noticed while br

3条回答
  •  故里飘歌
    2021-02-14 14:07

    Any ideas why this is not discussed/recommended more frequently?

    Placing JavaScript just before has been discussed a lot, and as you know it's recommended if you're looking for faster page loads. Manually triggering the jQuery ready handlers is in fact poorly discussed. Why? Well, I don't think there is one single objective answer to that, but I'll try to outline some possibilities here:

    1. Performance is not the main goal of jQuery (anthough it's definitely a concern), and performance freaks will usually look for lighter libraries for cross-browser DOM manipulation and event handling, or roll their own.

    2. It's an extra step, and it doesn't look clean. jQuery tries to be clean and elegant, and recommending an extra step to initialize scripts doesn't sound like something that's gonna happen. They recommend binding to ready, so recommending to force .ready() and ignoring the actual browser event looks "wrong". Whoever is concerned about that probably knows that initializing scripts right before is faster.

    3. Optimizing DOMContentLoaded sounds like a task for browser vendors. I'm not sure why it's slower, though, and maybe there's not much room for optimization – in my understanding, calling init scripts before should always be the fastest way to initialize stuff (as it's executed immediately when parsing the container

提交回复
热议问题