How can I wait for ` tags in your `` and just use a `load` Event? – StackSlave Apr 20 '20 at 03:08

  • Because the requirement is that it needs to be loaded afterwards. More context: it's a Cordova App and the required library is downloaded as On-Demand Resource from Apple servers. Unfortunately I cannot change that. – Gabe Apr 20 '20 at 03:09
  • Wrap your `injectScript` code in a `Promise`, resolve it when `script.onload` and reject when `script.onerror`. In your `start()` code, `await injectScript();` – JohanP Apr 20 '20 at 03:25
  • Replace `script.innerHTML` with `script.src = 'data:text/html,window.test = 1; console.log("test defined.");';` in addition to my previous comment about onload taking a function. Onload doesn't appear to get called for inline javascript. – Ultimater Apr 20 '20 at 03:34
  • @Ultimater That works, thanks! What about remote URLs though, will it work in that case? PS. yep, work with links too. – Gabe Apr 20 '20 at 03:57
  • 2 Answers2

    2

    Thanks to @Ultimater. This seems to work as expected:

    const script = document.createElement('script');
    script.src = 'data:text/html,id = 0;while(true){ if(++id==1000000) break;} window.test = 1; console.log("test defined.");';
    script.onload = () => console.log('onload called.', window.test);
    document.body.appendChild(script);
    
    Gabe
    • 5,997
    • 5
    • 46
    • 92
    0

    Try this:

    const injectScript = () => {
            const script = document.createElement('script');
            script.innerHTML = 'console.log("Function loaded..."); window.postMessage({cmd:"loaded"});';
            script.async = false;
            document.body.appendChild(script);
            }
    
            setTimeout(injectScript, 3000);
    
            window.addEventListener('message', function(e){
                if(e.data.cmd === 'loaded'){
                    console.log('external library loaded');
                }
            });
    
    Shine J
    • 798
    • 1
    • 6
    • 11