0

Can I run jquery code before DOM is loaded.

I want to run jquery on window.onload event.

I tried this :

window.onload=function($) {
  var url = $(location).attr("href");

        if (url.indexOf("1234") > 0)
            var nodeToHide = $('#1234');

            if(nodeToHide){
                var $parentToHide = $(nodeToHide).parent().closest("div[class='row']");
                if($parentToHide)
                    $parentToHide.hide();
            }
            };

But it gives an error.

EDIT I moved to plain js. Code is now:

<script type="text/javascript">
        function hideDiv1234() {
        var url = location.href;

        if (url.indexOf("1234") > 0){
            var headerToHide = document.getElementById('1234');

            var divParent = headerToHide.parentNode;
            if(divParent){
                divParent.parentNode.style.display="none";
            } else 
                divParent.style.display="none";
        }
    };      
    </script>

Unfortunately this function runs after page is shown on browser.

Vova Programmer
  • 335
  • 1
  • 3
  • 10

1 Answers1

1

If you want to run code before ready, you can remove it from ready callback and put it open inside script. It will be executed when the element is reached at the time of parsing HTML.

If you want to run code after all the resources are loaded, use load event on window:

jQuery(window).on('load', function ($) {
    // Your code here
}(jQuery));

For more clarification: https://stackoverflow.com/a/4584475/2025923

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179