Run Javascript after DOM is ready

  • Java
  • Thread starter Jamin2112
  • Start date
  • Tags
    javascript
In summary, 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)?If you want to define a function but not have it executed until after the DOM is ready, you can use a "callback function". A callback function is a function that is defined after the DOM is ready, but before any of the document's content has been executed.
  • #1
Jamin2112
986
12
... 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)?
 
Technology news on Phys.org
  • #3
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.
 
  • #4
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:
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
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/
 
  • #5
Filip Larsen said:
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?

Suppose I want to attach an event listener to an element:

Code:
$('#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.
 
  • #6
Is this what you meant by (1):
Code:
$(document).ready (function() {
    $('#my-element').hover(function(){ alert("Yo hovered over my element!") }); 
});
It appeared to work for me.
 
  • #7
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.
 
  • #8
harborsparrow said:
Sorry I can't really help you.

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.

harborsparrow said:
I'd probably end up doing something crass with a timer.

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.
 
  • #9
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
Silicon Waffle said:
http://javascriptkit.com/dhtmltutors/domready.shtml
Something similar can be achieved.

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.
 
  • Like
Likes Silicon Waffle
  • #12
harborsparrow said:
I notice that the fallback strategy in this article is--a timer!

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
[4] https://github.com/jquery/jquery/blob/master/src/core/ready.js
 
Last edited by a moderator:
  • Like
Likes Silicon Waffle and harborsparrow

Related to Run Javascript after DOM is ready

1. Why do we need to run JavaScript after the DOM is ready?

The Document Object Model (DOM) is a representation of the HTML elements on a webpage. Before the DOM is fully loaded, JavaScript cannot access and manipulate these elements. Therefore, it is necessary to wait for the DOM to be ready before running JavaScript to ensure that all elements are accessible.

2. How can I tell when the DOM is ready?

There are a few different ways to determine when the DOM is ready. One option is to use the DOMContentLoaded event, which fires when the initial HTML document has been completely loaded and parsed. Another option is to use the window.onload event, which fires when all assets on the page, including images and stylesheets, have finished loading.

3. What is the difference between using DOMContentLoaded and window.onload?

The main difference is that DOMContentLoaded fires when the HTML document has been loaded and parsed, while window.onload fires when all assets on the page have finished loading. This means that DOMContentLoaded may fire earlier than window.onload, but it does not wait for images and stylesheets to finish loading.

4. How can I run JavaScript after the DOM is ready using jQuery?

In jQuery, you can use the .ready() method to execute a function when the DOM is ready. This method is equivalent to using the DOMContentLoaded event. For example: $(document).ready(function() { // code to run after DOM is ready });

5. Is it possible to run JavaScript before the DOM is ready?

Technically, it is possible to run JavaScript before the DOM is ready by placing the script tag in the head of the HTML document. However, this is not recommended as it can cause issues with accessing and manipulating HTML elements. It is best practice to wait for the DOM to be ready before running any JavaScript code.

Similar threads

  • Programming and Computer Science
Replies
9
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
4
Views
767
  • Programming and Computer Science
Replies
8
Views
345
  • Calculus and Beyond Homework Help
Replies
3
Views
1K
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
9
Views
1K
Back
Top