Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Run Javascript after DOM is ready

Tags:
  1. Feb 15, 2015 #1
    ... the situation where you want a function to be defined after the DOM is ready, but don't want it to execute right when the DOM is ready (as happens if you simply put it in a document.ready(...) function)?
     
  2. jcsd
  3. Feb 16, 2015 #2
  4. Feb 16, 2015 #3

    TheDemx27

    User Avatar
    Gold Member

    The main mechanism being used in Greg's link is called a "callback function", which turns out to be pretty useful in many situations. You can go to this link: http://www.impressivewebs.com/callback-functions-javascript/ which explains it pretty well IMO.
     
  5. Feb 22, 2015 #4

    Filip Larsen

    User Avatar
    Gold Member

    It is a bit unclear to me why you would want to define but not invoke a function when the document is ready. Perhaps you can elaborate on what your problem is?

    If you really want to, you can just add a document ready handler that defines the function by simple assignment. Using the jQuery [1] document ready event [2] that could look like the following:
    Code (Javascript):

    var myFunction = function() {}; // define the symbol in current scope
    $(function() {
      var someValueFromDOM = ...;
      myFunction = function() {
        // use someValueFromDOM
      };
    });
     
    However, if you are using jQuery you can usually just define your function as normal and just use jQuery selectors [3] directly, like
    Code (Javascript):

    function myFunction() {
      var value = $('#my-text-element').text();
      // use value
    }
     
    But perhaps you are having a different problem?


    [1] http://jquery.com/
    [2] http://learn.jquery.com/using-jquery-core/document-ready/
    [3] http://learn.jquery.com/using-jquery-core/selecting-elements/
     
  6. Feb 22, 2015 #5
    Suppose I want to attach an event listener to an element:

    Code (Text):

    $('#my-element').hover(function(){ alert("Yo hovered over my element!") });
     
    If I also that function declaration in a JS file in the head, what happens is either:

    (1) I put it in a document.ready(...), in which case the alert will be invoked when the page is loaded.
    (2) I don't put it in a document.ready(...), in which case there's an error because #my-element isn't in the document tree at the time when the function is read.
     
  7. Feb 22, 2015 #6
    Is this what you meant by (1):
    Code (Text):

    $(document).ready (function() {
        $('#my-element').hover(function(){ alert("Yo hovered over my element!") });
    });
     
    It appeared to work for me.
     
  8. Feb 25, 2015 #7

    harborsparrow

    User Avatar
    Gold Member

    Welcome to the arcane world of Javascript load timing, and browser differences. Which is why I do as little Javascript as I can get by with. Sorry I can't really help you. I'd probably end up doing something crass with a timer.
     
  9. Feb 26, 2015 #8

    Filip Larsen

    User Avatar
    Gold Member

    I'm a little puzzled why you then choose to make a post, especially since the post just before yours provided an excellent code snippet showing the idiomatic way to do this in javascript with jQuery.

    Then you would most likely be doing it wrong. Javascript programming on the client (and server too for that matter) is highly asynchronous and event-driven, and understanding how this works is critical for making workable code.
     
  10. Feb 26, 2015 #9

    harborsparrow

    User Avatar
    Gold Member

    Just pointing out that timing is the hardest and probably most common Javascript problem, and not always straightforward to solve. I would want to test each solution mentioned here in all the browsers that need to be supported. In my experience, events often don't work alike in different browsers.
     
  11. Feb 27, 2015 #10
  12. Feb 27, 2015 #11

    harborsparrow

    User Avatar
    Gold Member

    I notice that the fallback strategy in this article is--a timer!!! Because IMO there is always the odd browser that just doesn't fire events in a sane order. Sigh. It's a good strategy, trying to account for everything and having a fallback plan for when it all fails. Better yet, would be to change to page design not to have to detect page loading--but I know it isn't always possible.
     
  13. Feb 27, 2015 #12

    Filip Larsen

    User Avatar
    Gold Member

    My point in post #8 was that a web page developer should never have to implement this themselves. A quick look at the domready code already mentioned, or the extensive code in jquery.documentReady [3], only confirms that this not something you can just throw together and expect to work in all cases. If backwards compatibility really is needed the developer should instead use one of the many polyfill libraries that have been extensively tested. And it is perfectly fine for such a library to use a recurrent timer as a fall-back strategy to detect when the document is ready.

    Regarding the current jQuery.ready() implementation [4] it should be safe to use in the sense that it will eventually fire, but maybe not as fast as one would like for some heavily framed pages on some old browsers. Note that it does not use timers, but relies solely on the HTML5 DOMContentLoaded [1] event with fall-back to the window.load event [2].

    [1] https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
    [2] https://developer.mozilla.org/en-US/docs/Web/Events/load
    [3] https://github.com/addyosmani/jquery.parts/blob/master/jquery.documentReady.js [Broken]
    [4] https://github.com/jquery/jquery/blob/master/src/core/ready.js
     
    Last edited by a moderator: May 7, 2017
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Run Javascript after DOM is ready
  1. Javascript Help (Replies: 4)

  2. Frontpage JavaScript (Replies: 3)

  3. Javascript problem (Replies: 6)

Loading...