Search code examples
jquerydelay

jQuery annoying initial delay


Brief

I do not have any specific code to show, but a general question. Whenever i use jQuery, it always has a 1000-2000ms delay, before actually becoming active. How can i fix this?


Example

$(document).ready(function(){
    setInterval(function(){
        alert('This has been delayed more than necessary.');
    }, 1000);
}

It takes 2000ms for it to initiate. I've been struggling with this problem for a long time, but i simply can't find an answer around the web. I have already searched both Stack Overflow and Google.


Thanks in advance.


Solution

  • I don't think jQuery is intentionally delaying the execution of your code. You have two layers of callbacks here:

    // here you are waiting for the HTML markup to finish being parsed
    // and turned into a usable DOM (this is the "DOM-ready" event)
    $(document).ready(function() {
        // This code does not run until the DOM is ready. Then, you delay
        // your alert by another 1 second by using this setInterval here
        setInterval(function(){
            // This will not happen for 1000ms after the DOM is ready
            alert('This has been delayed more than necessary.');
        }, 1000);
    }
    

    Even if your page was empty, you are delaying your code by a minimum of 1 second.

    The rest of it may be due to having a large page, loading many scripts, large CSS files or font files. Check your browser's "Network" tab in its development tools to see the timings of your page loading.

    FYI, if you structure your page the "best practice" way, it would look something like this:

    <html>
    <head>
        <script src="external/reference.js"></script>
    </head>
    <body>
        <!-- All your HTML are belong to us -->
        <script type="text/javascript">
            // put your code here, in a <script> tag right before the 
            // closing </body> tag
            alert('I'm ready!');
        </script>
    </body>
    </html>
    

    ...and it would not require the DOM-ready handler or the setTimeout function -- it simply would not run until the rest of the page has finished loading.