Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine if a function is running in document ready or not?

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.)

like image 685
g.pickardou Avatar asked May 26 '15 11:05

g.pickardou


People also ask

How do I know if my document is ready?

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.

Can we define function in document ready?

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.

What is difference between document ready and $function?

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).

How do you call a function after document ready?

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().


1 Answers

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.

like image 200
Gone Coding Avatar answered Sep 29 '22 18:09

Gone Coding