javascriptjquerydomready

Is it safe to call jQuery methods before DOMReady?


We have a project where jQuery is concatenated into our main javascript application JS file, and I was wondering if it is safe to call jQuery methods before DOMReady?

I see many websites suggest triggering your jQuery javascript after DOMReady, for example:

$(function(){
  $.each(myObject, function(index, val) {
    ...
  });
});

However, this seems to delay the script execution, sometimes causing issues with other application functionality. Since jQuery is already included in the same JS file (at the top), would it not be safe to trigger jQuery methods without waiting for DOMReady?

$.each(myObject, function(index, val) {
  ...
});

In my tests, it works fine, but I just want to make sure I'm not left to browser randomness. I'm assuming it's fine to run jQuery methods as long as it goes below jQuery definition, and as long as it's not DOM-related activities. Thanks for any input.


Solution

  • You can make any jQuery calls before DOMReady. One thing to keep in mind is that if you refer to DOM elements, the executed code will be applied only to the elements already existed in DOM.

    For example:

    <div class="item">
    
    </div>
    <script>
        console.log(jQuery('.item').length); // It will output 1
    </script>
    <div class="item">
    
    </div>
    <script>
        console.log(jQuery('.item').length); // It will output 2
    </script>
    

    Using the DOMReady event to make your initializations is simply a practice to ensure that all elements exist in the DOM.