Run JavaScript Only After Entire Page Has Loaded

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

Comments

  1. User Avatar
    Baylor Rae'
    Permalink to comment#

    This should go in jQuery

  2. User Avatar
    Rory McCrossan
    Permalink to comment#

    A shorthand version of this is:

    $(function() {
    // code here
    }

    • User Avatar
      Chris Coyier
      Permalink to comment#

      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.

    • User Avatar
      test
      Permalink to comment#

      $(function() {
      // code here
      }

    • User Avatar
      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.

    • User Avatar
      Patrick
      Permalink to comment#

      Thanks @Makaze!

    • User Avatar
      Aldi Unanto
      Permalink to comment#

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

    • User Avatar
      sreejith
      Permalink to comment#

      this one wont work…..this may be short…but wont work

    • User Avatar
      jD
      Permalink to comment#

      i need demo link for this

  3. User Avatar
    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!

    • User Avatar
      Mike Smith
      Permalink to comment#

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

    • User Avatar
      Artur Ejsmont
      Permalink to comment#

      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. User Avatar
    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. User Avatar
    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. User Avatar
    jon
    Permalink to comment#

    // just another way to write the same thing.

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

  7. User Avatar
    Ahxan Khan
    Permalink to comment#

    how can i add this to blogger template??

  8. User Avatar
    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. User Avatar
    Anything Graphic
    Permalink to comment#

    Genius! Thank you so much :-)

  10. User Avatar
    Andy
    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. User Avatar
    aditia
    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. User Avatar
    mark
    Permalink to comment#

    Shame it doesn’t work in IE9 :-(

    • User Avatar
      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

    • User Avatar
      ingvi Jónasson
      Permalink to comment#

      @mark
      Do you have jQuery load before?

  13. User Avatar
    Dan Voyce
    Permalink to comment#

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

  14. User Avatar
    RITURAJ
    Permalink to comment#

    working…..

  15. User Avatar
    Cody Sielawa

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

  16. User Avatar
    ian.pvd
    Permalink to comment#

    Holy crap. This just saved my life.

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

  17. User Avatar
    James Hambly
    Permalink to comment#

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

    Thanks!

  18. User Avatar
    Domina X
    Permalink to comment#

    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.

    • User Avatar
      jamie paterson
      Permalink to comment#

      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. User Avatar
    Romans
    Permalink to comment#

    This is the most awesome website about web development!

  20. User Avatar
    Rajiv Varma N
    Permalink to comment#

    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. User Avatar
    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. User Avatar
    Jubal
    Permalink to comment#

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

  23. User Avatar
    Alexandru Nastase
    Permalink to comment#

    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. User Avatar
    Thomas Kroell
    Permalink to comment#

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

  25. User Avatar
    David
    Permalink to comment#

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

  26. User Avatar
    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

    • User Avatar
      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. User Avatar
    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. User Avatar
    Visvanathan

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

  29. User Avatar
    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. User Avatar
    zMin
    Permalink to comment#

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

  31. User Avatar
    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 ?

    • User Avatar
      Jon Barratt
      Permalink to comment#

      Did you get an answer to this question, bonaca? I’m struggling with the same issue.

  32. User Avatar
    Sathish
    Permalink to comment#

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

  33. User Avatar
    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. User Avatar
    Rick
    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. User Avatar
    Ganeshkumar.S
    Permalink to comment#

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

  36. User Avatar
    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. User Avatar
    vikash
    Permalink to comment#

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

  38. User Avatar
    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. User Avatar
    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. User Avatar
    thecristen
    Permalink to comment#

    This helped me so much! Thank you!

  41. User Avatar
    javier
    Permalink to comment#

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

  42. User Avatar
    Scott
    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. User Avatar
    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. User Avatar
    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. User Avatar
    Jamil
    Permalink to comment#

    AWESOME man. I owe you a beer.

  46. User Avatar
    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. User Avatar
    Garrett
    Permalink to comment#

    Non-jquery:

    <head>
    
    function func() {
        alert("hello world");
    }
    
    </head>
    
    
    <body onload="javascript:Func()"></body>
    
  48. User Avatar
    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. User Avatar
    shamim
    Permalink to comment#

    It helps me. Thank you.

  50. User Avatar
    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. User Avatar
    Kim
    Permalink to comment#

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

  52. User Avatar
    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

  53. User Avatar
    Bhumi
    Permalink to comment#

    Thanks for your code but i want to submit form on page load only once but it goes in loop. is there any solution?

    $(window).bind(“load”, function() {
    // code here
    $( “#id” ).submit();
    });

  54. User Avatar
    zahra
    Permalink to comment#

    how can i run jquery code after load another pages???

  55. User Avatar
    cheeky bob
    Permalink to comment#

    this even works in Sharepoint environments! Great

  56. User Avatar
    Mal

    Thank you so much, really needed to understand how to do this for a site with inter-dependent dynamic div heights. Genius.

  57. User Avatar
    Bhavin
    Permalink to comment#

    Without including jQuery and with pure javascript:

    window.onload = function () { alert(“It’s loaded!”) }

  58. User Avatar
    Sazz
    Permalink to comment#

    Thank you sooooo very much :)

  59. User Avatar
    Jay Sax
    Permalink to comment#

    Based on my reading today I believe that the jquery way now is

    $(window).on("load", ...)
    

    Rather than .bind() or even .load().

    In case someone else knows, in a related vein, I’d be happy to hear something authoritative on whether this waits until even iframes are finished loading.

    It appears that $(window).on(“load”…) does not wait for iframes to load, but I could be missing something.

    Jay

  60. User Avatar
    Optimus Prime
    Permalink to comment#

    Nice, i was wondering about there uses, We can do many necessary thing when is page is loaded

  61. User Avatar
    Harry Pujols
    Permalink to comment#

    The vanilla JavaScript version

    window.onload = function(){
        // code here
    };
    
  62. User Avatar
    Watt
    Permalink to comment#

    Useful ONLY if you’re using jQuery already.
    However, I don’t see the point of overloading the page with another .js (ie jQuery) just to instruct the browser to delay the other scripts.

  63. User Avatar
    ben cavallaro
    Permalink to comment#

    thanks. i was having trouble running a script on page load that required the entire page to be loaded including binding of data and application of scripts that changed DOM on the .ready event. once i moved the code out of .ready and into this, it worked.

  64. User Avatar
    Rohidas
    Permalink to comment#

    Hi,

    I have to scrollTop by selecting the element rendered using AJAX. How can I do it.

    I used all tricks like settimeout,document.ready,ajax complete,ajax done but no success. Kindly help.

  65. User Avatar
    Joe Audet
    Permalink to comment#

    Thanks much – this helped me out a lot. I was having trouble with loading in code from another central HTML file and then updating it. In this case it was the bootstrap navbar I wanted to change the active class on.

  66. User Avatar
    Palash Sachan
    Permalink to comment#

    how can i auto click button when the page is loaded inside $(windows).load

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag