Trigger callback function when two event listeners are fulfilled

I am looking for an elegant way to call a callback function when two load event listeners are fulfilled. Currently I am using a variable which has the state of the event listener and is checked in an interval. This is an example of my depicted situation:

function executeExtScript(cb, srcStyle, srcJs) {
    let scripts = document.getElementsByTagName('script');
    let scriptExists = false;
    for (let i = scripts.length; i--;) {
        if (scripts[i].src === srcJs) scriptExists = true;
    scriptExists === true ? cb() : loadScript();
    function loadScript() {
        let loadFinish = [false, false];
        let head = document.head;
        let style = document.createElement("link");
        style.setAttribute("rel", "stylesheet");
        style.setAttribute("href", srcStyle);
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = srcJs;
        script.onload = () => {loadFinish[0] = true}
        style.onload = () => {loadFinish[1] = true}
        var timer = setInterval(function(){
            if (loadFinish[0] && loadFinish[1]) {
            }, 100);

Is there any more elegant way to solve this problem - in particular I would like to prevent using a se timeout function provided that they may run for a very long time if I fail to fetch one of the files

Thanks in advance

Read more here:

Content Attribution

This content was originally published by Jakob at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: