Is there a way to determine if a function is running in document ready?
I mean something like this:
function myfunction() {
var isinside = //... what to write here?
if (isinside) {
}
}
(It is also possible my (very beginner) concept is not optimal, so I write what I am trying to achieve:
I would like to create a reusable object, what can instantiated in multiple instances within a page (hopefully with one line of JavaScript per instance). However there are things what this object must do in document ready, like attaching event handlers.)
To check if the document is ready and run some code, you can add an event handler to the DOMContentLoaded event of the document object. The DOMContentLoaded event is fired when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
There is no difference in functionality between your examples - they both bind to DOM ready. For reference, there are two points at which you can bind your jQuery code. The first will execute when the DOM is ready (both are equivalent): // full example $(document).
So, there is no event called after document. ready(). You'll need to create and wait for events to complete on your own, or use window. load().
I am not sure why you have a problem here? The calling code is normally responsible for being in a DOM ready handler, or not, not the functions.
You can just put a DOM ready redundantly inside any function, if needed, but this sounds like an odd situation so you need to show the rest of the code.
e.g. any function can have a DOM ready handler:
function myfunction() {
$(document).ready(function(){
// I am inside DOM ready!
// Connect my DOM element events here
});
// Do my other non-element stuff here
}
or, shorter:
function myfunction() {
$(function(){
// I am inside DOM ready!
// Connect my DOM element events here
});
// Do my other non-element stuff here
}
The key here is that DOM ready handlers can be called after DOM ready and they fire immediately.
The downside to this is that you cannot rely on a return value as DOM ready is potentially async.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With