jQuery best practices in case of $('document').ready

前端 未结 9 1283
孤街浪徒
孤街浪徒 2020-12-07 11:35

I was researching on jQuery best practices and found this article by Greg Franko

Normally, I do:

$(\"document\").ready(function() {
    // The DOM i         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 11:58

    1. $(function(){}) is equivalent to $('document').ready(function(){});. It's up to you which you use, but the latter is the older of the two, and more verbose to boot.

    2. The second approach you have listed is an explicit attempt to prevent global variables, and injects the known globals $, window, and document. This is recommended to increase awareness of how easily globals are introduced, and be as 'clean-room' as possible about the code we are injecting to the page. Also, note that the second approach is not equivalent to the first if you follow the comments shown. Because $ is inserted as an argument, this code is compatible with other libraries that may desire to own the $ symbol.

    In particular, // The rest of the code goes here is in a place that may be executed before the document is ready, or when that event is fired. Put it inside the function passed to $.

提交回复
热议问题