Grow your CSS skills. Land your dream job.

Last updated on:

Run JavaScript Only After Entire Page Has Loaded

$(window).bind("load", function() {
   // code here
});

Comments

  1. This should go in jQuery

  2. A shorthand version of this is:

    $(function() {
    // code here
    }

    • There is a fundamental difference there. That is is when the DOM is ready, which is usually ideal. This is when the whole page has finished loading, which is different. For example, this will wait for images to be finished loading, so that you can measure their widths and heights accurately while your snippet will not wait. Small but sometimes crucial difference.

    • Permalink to comment#

      $(function() {
      // code here
      }

    • Makaze
      Permalink to comment#

      Your syntax is incorrect as well. It should be:

      $(function() {
      // code here
      });

      Be sure to close those brackets and end with a semicolon.

    • Permalink to comment#

      Thanks @Makaze!

    • There is difference between
      $(function() {
      // code here
      }
      and $(window).bind("load", function() {
      // code here
      });
      . $(window).bind(‘load’, function(){}) will run after page has loaded.

  3. Rodrigo
    Permalink to comment#

    This is probably my first comment on your site and I’ve been a fan and reading for a long while probably since podcast 20 XD

    I haven’t been able to figure out where to place this code..?

    If you can help me out, give me an example with your “simple jquery accordion” – http://css-tricks.com/snippets/jquery/simple-jquery-accordion/

    Thanks, Chris!

    • Place the code in your <head>HERE</head> section.

    • it depends how much code you have and if you are erver going to reuse. If you want to reuse put function in the JS file with reference to a variable that lives in

      Then you can put any id you want per page and if item of this id exists it will be processed.

      so in JS file you dont hardcode stuff that much just check if varialbe is ther and what is the value.

      for this example i guess it would be an overkill

      :- )

  4. ChromA
    Permalink to comment#

    Is there way to do this without jQuery? I use jQuery (but the script will be loaded at page-end). I’m looking for a JS-Snippet to use in the Content (that will be executed when the page has loaded.

  5. mathew
    Permalink to comment#

    Small thing. When using the button “copy to clipboard” it will copy it with curly ‘”‘ and not just straight “. With the curly ones the code doesn’t work…

    Thanks

  6. jon
    Permalink to comment#

    // just another way to write the same thing.

    $(window).load(function() {
    // everything’s finished loaded code here…
    });

  7. how can i add this to blogger template??

  8. bekir
    Permalink to comment#

    I’m trying to load page before load the map ( I use is map extreme ) although I use document ready function, the page trying to load mapLabels with page objects. for a while user see my page as there is no css. After the map finished it’s job the css loaded. How can I fix this? I use your code but it didn’t work for me.

    Here is an example;

    j(window).bind(“load”, function () {
    MapXtremeJavascriptLib.init();
    });

    /* DOCUMENT READY FUNCTION AREA START */
    j(document).ready(function () {

    j(“.accordion”).accordion({
    autoHeight: true,
    navigation: true,
    collapsible: true
    });
    /* DOCUMENT READY FUNCTION AREA END*/

  9. Genius! Thank you so much :-)

  10. Permalink to comment#

    Hi all,
    I’m battering my head about how I can A: Tell a javascript to wait till the entire site has loaded. I guess I just found the solution to that. And B: Have the javascript load only on the home page.

    The site runs on joomla and before I had the script run from a custom html module which I had assigned to the debug position and set to only load on the home page.

    That worked fine for firefox, chrome and safari but IE was mocking up (as usual).

    Now I’m battering my head about how I can add it so that the script (a lady walking into the site and welcoming the visitors) will only show on the home page.

    I appreciate any suggestions!

    Thanks in advance,
    Andy

  11. Permalink to comment#

    thanks, chris before knowing this I used setTimeout, and the bad thing using this, is we never exactly know how long the page load time on the user browser

  12. Permalink to comment#

    Shame it doesn’t work in IE9 :-(

    • Ben Riordan

      $(window).load(function()

      Should work fine on IE9. At least it is for me. Doesn’t work on IE8 and below though.

      What it doesn’t work on however if the current version of Firefox. Apparently firefox treats .load and .ready as the same and loads .load after the javascript has loaded and doesn’t wait for all images and other page content like the other browsers do. Does anyone know of a workaround for firefox?

      Thanks

      ~ Ben

    • @mark
      Do you have jQuery load before?

  13. Dan Voyce
    Permalink to comment#

    Your averaging 1 answer a day for me. Thank you very much!

  14. RITURAJ
    Permalink to comment#

    working…..

  15. This is exactly what I needed, Thanks for the great resource!

  16. Holy crap. This just saved my life.

    … yes, I might be exaggerating, but not by much.

  17. After spending about four hours trying to get some externally sourced code to cycle with jQuery cycle, this snippet solved everything.

    Thanks!

  18. Great… jQuery again. Looking at the title in Google, I thought you were going to present something non-framework. Bah, why do people ignore the fact that it’s not cool to load a 32KB jQuery lib for something that could be done in a few lines.

    Thanks anyway… even when this didn’t help me at all.

    • You and your users probably have jQuery cached on their systems so I guess not an issue – plus if you use Google as the CDN its blindingly fast – so why not?

  19. Romans
    Permalink to comment#

    This is the most awesome website about web development!

  20. I want to Load my Minified JS after the page load.
    Currently it takes 1.8 sec to 2.5 sec to load this JS File which is increasing my complete webpage load to 4.2 sec to 5.1 sec.

    So how can i load this JS without delaying the page load.

  21. Doug T
    Permalink to comment#

    As always, jump on google have a nosey and the first result from Css-Tricks is the winner on the day!, Cheers for your time invested in the web dev commnity Chris.

  22. Jubal
    Permalink to comment#

    $(window).on(‘load’, function(){
    // AWESOMENESS
    })

  23. This snippet made my day Chris thank you a many man, I’m finding more and more useful things on your website for my front-end development, thanks !!

  24. Thank you! Been struggling to get Jquery to load after a ton of images have been loaded and this just works perfectly!

  25. David
    Permalink to comment#

    As Jubal points out .bind has been deprecated in flavor of .on

  26. Riya

    $(window).bind(“load”, function(){
    });
    The above function works fine only on the initial load. But when we navigate to differect page and come back to the same page. the function gets executed before complete loading of Dom elements. Kindly tell me if there is another way

    • Sandeep
      Permalink to comment#

      Are you using jquerymobile? Check if the responses to your buttons / links is being added to the same DOM. Use firefox or firebug to determine this. If yes, then it is because in jquerymobile the mode is default ajax. You will need to use ‘rel=”external”‘ in your links to make it work right or re-write the code to get it to work properly within the framework.

  27. Shawn
    Permalink to comment#

    Excellent post! Was trying to use the DOM ready one instead of html layout in my app and immediately noticed why I wasn’t able to insert html. :) Thanks!

  28. Visvanathan

    how to run window.load event only once in web page

  29. Tony

    This does not work in Firefox at all :(

    Thought I was crazy but it most certainly does not…

    $(window).bind(“load”, function() {
    alert(‘test’);
    });

    Try that code snippet in chrome it alerts test… in firefox, nothing. I am on the current version of firefox (v 22).

    Does anyone know a way to do this that works cross browser.

  30. Permalink to comment#

    Is there any way to implement this while loading remote scripts?
    E.g.:
    Thanks.

  31. bonaca
    Permalink to comment#

    I must repeat Riya’s question:

    $(window).bind(“load”, function(){
    });
    The above function works fine only on the initial load. But when we navigate to differect page and come back to the same page. the function gets executed before complete loading of Dom elements. Kindly tell me if there is another way ?

  32. Permalink to comment#

    Nice Post. What is the difference between bind and live?

  33. Aaron Loften
    Permalink to comment#

    Thank you. You always have great web design suggestions. It kinda seems like everyone else out there is saying to use .live() which(according to my research) is depreciated. Even if its not, this rocks! Thanks!

  34. Permalink to comment#

    This code did the job for Woontrendz to prevent a sticky ‘top of the site’ navigation from breaking when scrolling while the page is still loading CSS/JS/Images:

    $(window).load(function() {
    });
    

    Thank you so much!

  35. Ganeshkumar.S
    Permalink to comment#

    How to call click event after the page loaded in jquery?

  36. Ganeshkumar.S
    Permalink to comment#

    I need to execute the this function after the page load.

        $("#video_publish_status").click(function(){
              alert(location.href);
          });
    

    Please help me…

  37. vikash
    Permalink to comment#

    It really works!!!! it solved my problem.

  38. Gurunathan
    Permalink to comment#

    $(window).bind(“load”, function() {

    });

    This Code Not Correctly Work In IE9 Before Some page Load This Function Fire…

    Any Help For WINDOWS.Load Function For IE support

  39. Alex
    Permalink to comment#

    if (document.readyState === “complete”) { init(); }
    /*
    ninitialized – Has not started loading yet
    loading – Is loading
    interactive – Has loaded enough and the user can interact with it
    complete – Fully loaded
    */

  40. thecristen
    Permalink to comment#

    This helped me so much! Thank you!

  41. javier
    Permalink to comment#

    You ROOOOOOOOCK!!!!! Thank you SO much!
    This works perfect.

  42. Permalink to comment#

    Referring to Chris’s suggestion: $(window).bind(“load”, function() {

    This is an excellent function to use and loads after ALL JavaScript and AJAX/JSON loads on the page. It also works in IE9.

    I develop front end SharePoint solutions and Chris’ suggestion is the ONLY one that has worked for me for loading after the whole page.

    Much thanks!

  43. Robby
    Permalink to comment#

    Interesting thanks BUT how can I make a YouTube embedded video wait until the scripts have loaded on a page?
    At the moment if the impatient click an image and launch the Lightbox it does not show the zoomed image as it should, rather it just shows the zoom as a seperate page; this diesn’t happen after the video is loaded so it’s obviously the video loading which is stopping the lightbox script from loading.
    ???

  44. Shawn
    Permalink to comment#

    Was looking this up and found a supposedly Google-recommended, cross-browser method that does the same thing:

    <script type="text/javascript">
    function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
    }
    if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
    else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;
    </script>
    

    Source: Feedthebot

  45. Jamil
    Permalink to comment#

    AWESOME man. I owe you a beer.

  46. Stéphan Champagne
    Permalink to comment#

    Thanks you so much,
    I was having a hard time with columns height because of images not being loaded before jquery.ready was run. Only on refresh, on chrome. But a pain to figure out.
    When I put an alert, I could see the images where not loaded when the alert triggered. So I search for the reason and this so “small but sometimes crucial difference” made it work.
    Thanks

  47. Non-jquery:

    <head>
    
    function func() {
        alert("hello world");
    }
    
    </head>
    
    
    <body onload="javascript:Func()"></body>
    
  48. Ted
    Permalink to comment#

    This helped me out so much.

    I had a reportviewer control that wouldn’t print from window.onload.
    This fixed the issue.

    Thanks again

  49. shamim
    Permalink to comment#

    It helps me. Thank you.

  50. George John
    Permalink to comment#

    I tried the above code, it seems fine. I have one doubt regarding asynchronous JS. Will the Onload event get fired after loading all the asynchronous js files or after HTML rendering.

    Also is there any way, we can prioritize the asynchronous calls ?

  51. Kim
    Permalink to comment#

    Thanks for sharing the knowledge! The code and explanation helped a lot!

  52. Jamil Ahmed
    Permalink to comment#

    Awesome and very useful trick. I was trying some jquery at page in the end but its not working, then I found this trick and hola it works perfect. Now I can load my code after whole page loads. Thanks Chris for sharing

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".