0

I load my Javascript from CDN using code below:

function LoadScript(href, integrity) {
    var script = document.createElement("script");
    script.type = 'text/javascript';
    script.src = href;
    script.async = false;
    if (integrity) {
        script.integrity = integrity;
        script.crossOrigin  = "anonymous";
        script.referrerPolicy = "no-referrer";
    }
    //document.currentScript.after(script);
    document.head.appendChild(script);
}

Regardless of where I invoke and place those JS files, they are always executed after static JS files which are already present in the HTML.

s k
  • 4,342
  • 3
  • 42
  • 61
  • 3
    Does this answer your question? [Immediately execute dynamically loaded JS script](https://stackoverflow.com/questions/51966474/immediately-execute-dynamically-loaded-js-script) – Nico Haase Jan 20 '23 at 13:40
  • Does this answer your question? [load and execute order of scripts](https://stackoverflow.com/questions/8996852/load-and-execute-order-of-scripts) – Jan Pfeifer Jan 20 '23 at 14:13
  • Guys, the code that I have posted above had already set `async = false` and put into the head section. My problem is the execution order of the dynamically vs static javascript. Even when the dynamically javascripts are loaded in order and put at the beginning of the head section, they are still executed after statically loaded javascripts. – s k Jan 20 '23 at 21:55

1 Answers1

-2

Have you tried async/await?

This will force the browser to wait for the loadScript function to resolve before executing the rest of your code.

async function loadScript(href, integrity) {
    return new Promise(resolve => {
        var script = document.createElement("script");
        script.type = 'text/javascript';
        script.src = href;
        if (integrity) {
            script.integrity = integrity;
            script.crossOrigin  = "anonymous";
            script.referrerPolicy = "no-referrer";
        }
        script.onload = resolve;
        document.head.appendChild(script);
    });
}

await loadScript("yourScript.js", "yourIntegrity");
ben
  • 49
  • 8
  • Please add some explanation to your answer such that others can learn from it – Nico Haase Jan 20 '23 at 14:37
  • 1
    @NicoHaase Added a description. – ben Jan 20 '23 at 14:48
  • 1
    @ben thanks for the answer. While this may load the dynamically loaded libraries in order, they are still loaded after those libraries that are load statically. – s k Jan 20 '23 at 22:18
  • @sk Can you give more context about the HTML you're working with? Is it an HTML file you have control of or are you creating a script for a website where you can't edit the HTML? – ben Jan 21 '23 at 11:23
  • @ben It is in a pure HTML page (with no code behind) where I need to load some themes / locale libraries dynamically (depends on user's preference / locale setting) before my own JS files which are loaded statically. – s k Jan 24 '23 at 07:29