简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM