Mini script to inject javascript script runtime. Useful to manage cookie policy.

function doInjectScript(path, charset, defer) {
    if (!path) {
        console.warn("Invalid path");
        return;
    }
    let sc = document.createElement('script');
    let nid = btoa(path);
    sc.setAttribute("id", nid);
    sc.setAttribute("type", "text/javascript");
    sc.setAttribute("src", path);
    sc.setAttribute("charset", charset ? charset : "UTF-8");
    if (defer) {
        sc.setAttribute('defer', '');
    }
    let scriptsInPage = document.getElementsByTagName('script');

    /** append only if not found */
    let found = false;
    for (let curScript of scriptsInPage) {
        if (curScript.id == nid) {
            found = true;
            break;
        }
    }
    if (!found) {
        let lastSt = scriptsInPage[scriptsInPage.length - 1];
        lastSt.parentNode.insertBefore(sc); //insert before the last one
        //lastSt.parentNode.insertBefore(sc, lastSt.nextSibling); //insert before the next sibiling - useful in some cases
    }
}

/* usage */
doInjectScript("https://yourscript.js");
doInjectScript("https://yourscript.js", "UTF-8");
doInjectScript("https://yourscript.js", "UTF-8", true);
Categories: Js,Ts,Css

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.