Detect if any JavaScript function is running

前端 未结 3 926
离开以前
离开以前 2021-02-19 03:51

I know it may sound very strange, but I need to know if there is any active/running javascript in the page.

I am in situation in which I have to run my javascript/jquery

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 04:27

    There is no definitive way to do this because you can't really know what the latest is that other scripts have scheduled themselves to run. You will have to decide what you want to target.

    1. You can try to run your script after anything else that may be running when the DOM is loaded.
    2. You can try to run your script after anything else that may be running when the page is fully loaded (including images).

    There is no reliable, cross-browser way to know which of these events, the scripts in the page are using.

    In either case, you hook the appropriate event and then use a setTimeout() to try to run your script after anything else that is watching those events.

    So, for example, if you decided to wait until the whole page (including images) was loaded and wanted to try to make your script run after anything else that was waiting for the same event, you would do something like this:

    window.addEventListener("load", function() {
        setTimeout(function() {
            // put your code here
        }, 1);
    }, false);
    

    You would have to use attachEvent() for older versions of IE.

    When using this method, you don't have to worry about where your scripts are loaded in the page relative to other scripts in the page since this schedules your script to run at a particular time after a particular event.

提交回复
热议问题