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

前端 未结 9 1290
孤街浪徒
孤街浪徒 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:50

    Your link has the anwser:

    The below is fine,

    If you know the environments where your code will run.

    If you do not care about page load performance.

    If you don't care about best practices.

     $("document").ready(function() {
        // The DOM is ready!
        // The rest of the code goes here
      });
    

    But they recommend, its better to use like below for, If you don't know the environment where your code will run and

    Better page load performance

    // IIFE - Immediately Invoked Function Expression
      (function($, window, document) {
    
        // The $ is now locally scoped 
    
       // Listen for the jQuery ready event on the document
       $(function() {
    
         // The DOM is ready!
    
       });
    
       // The rest of the code goes here!
    
      }(window.jQuery, window, document));
      // The global jQuery object is passed as a parameter
    

提交回复
热议问题