Last Updated:

Increase Website Page Speed to load jQuery at last

increase Website Page Speed
 
Let's imagine the moment when the jQuery library is loaded at the end of the body tag, but you need to run some script before the library is called.

I'll tell you right away that you'll still have to wait for the library to load. This article will describe how to load a jQuery script after the page is fully loaded.
 


Attempting to invoke the script before the library is called will result in an error similar to the following:

ReferenceError: $ is not defined

The error tells us that the character ($) is not defined and is unknown to the browser.

Sample code that will lead to an error:


The rescue in this situation is to call the window.onload event.

The onload event on the window is triggered when the entire page, including the resources on it – styles, images, etc. – is loaded.

Sample working code:


Wrap your code in the window.onload event and your code will have to run (If of course the code will work).


The code will now be processed by the browser after the page is fully loaded.
<body>
<input name="name" id="name" value="name"type="submit">
<script>
        $('#name').click(function() {
            alert("JQuery Running!");
        });
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
<body>
<input name="name" id="name" value="name"type="submit">
<script>
    window.onload=function(){
        $('#name').click(function() {
            alert("JQuery Running!");
        });
    }
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
window.onload=function(){
// Your code
}