[removed] and $(document).ready

后端 未结 4 1330
囚心锁ツ
囚心锁ツ 2020-12-14 14:50

According to http://caniuse.com/script-defer, most browsers support the script tag\'s defer attribute.

I would like to know if scripts spec

相关标签:
4条回答
  • 2020-12-14 15:26

    The defer attribute has a good write-up and analysis. Also See the comments to the post for additional info on how defer has been re-defined in HTML5.

    My conclusion: defer is too browser dependent to count on. Therefore use the jQuery doc ready technique.

    To put it another way, an important reason for jQuery is to cover browser inconsistencies. Defer is another such inconsistency that should be avoided for well written pages.

    0 讨论(0)
  • 2020-12-14 15:33

    To defer inline javscript you can use type="module" which then makes $(document).ready() redundant.

    <script type="module">alert('defered inline js')</script>
    

    Because type="module" implies defer scripts will execute in order with other deferred scripts.

    See can I use 92% browser support in September 2020. https://caniuse.com/es6-module

    0 讨论(0)
  • 2020-12-14 15:47

    Simply, script should be executed before $(document).ready() whether defer is used or not and almost all major browsers support defer.

    But for being safe side I encourage you to use both $(document).ready() and defer. So why defer? Because it helps page appear quickly (as external script is loaded parallel) and a really important factor in Google's page speed tool, a good detail can be found here http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS

    0 讨论(0)
  • 2020-12-14 15:51

    Based on this fiddle I have to say jQuery's $(document).ready() executes after a script declared with defer. I tested it with Firefox and Chrome, and both had the same behavior independently of the sequence of the scripts.

    I guess behavior on other browsers might change based on their implementation, so it's always uncertain.

    EDIT: As it turns out, the defer attribute should be used with an external javascript file. I edited the fiddle to show this, apparently with the same results.

    Updated fiddle here: http://jsfiddle.net/RNEZH/15/

    0 讨论(0)
提交回复
热议问题