How can I be sure that one of the js injections on the page has an uncertain time and provides a ready event, so how can I make sure that it exists when I use it?

for example, there is a global variable STS . The js file in which this variable is located is injected into our page by the client. After it is injected into the page and initialized, a ready event is executed. However, the injection time of this js file cannot be guaranteed. We can only check it every time. If it exists, we can use it directly. If it does not exist, we need to ready:

function BB(){

}
var bb = new BB();
bb.invoke("showTip", Date.now());

like this, wrap it through BB, and then I can use it directly later, so I can call the showTip method in STS instead of checking STS every time. Thank you

Mar.30,2021

feels that this solution introduces a lot of problems; in that case, if the injected JS file does not contain dynamic content, can it be packaged into SDK and directly used by the front end?


create an array of tasks and listen to the array object. Store the callback that needs to be executed when sts does not exist. When the ready is completed and the array changes, check the callback queue length and then delete the callback in the task queue array so that you don't have to worry about whether it is loaded or not. Tasks will be suspended in turn if it is not loaded. After loading, you will first put a task into the task queue, and then immediately take it out and execute


write a ready function using Promise, and then call it:

class BB {
    __ready = false;

    constructor() {

    }

    ready() {
        if (this.__ready || window.STS) {
            return Promise.resolve(window.STS);
        }
        return new Promise((resolve) => {
            document.addEventListener('stsready', function(){
                this.__ready = true;
                resolve();
            })
        })
    }

    async invoke(fn, ...params) {
        await this.ready();
        fn.bind(null, ...params);
    }
}

var bb = new BB();
bb.invoke('showTip', Date.now());
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c1e3-2c2e4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c1e3-2c2e4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?