Check if Javascript script exists on page

后端 未结 7 735
深忆病人
深忆病人 2021-02-02 10:16

I have a bookmarklet that I\'ve made and it loads a script from my server onto the users current page. However I have an if check in my script that if a condition is not met the

7条回答
  •  一生所求
    2021-02-02 10:54

    In case working with local and live alternatively.

    The exact URL may change. I think the ID method is better.

    This is a combination of Two StackOverflow answers.

    if (!document.getElementById('your-id')) {
            addScript("your_script_src"); //adding script dynamically
            addCSSFile("your_css_src"); // adding css files
    }
    
    function addScript(path) {
            var head = document.getElementsByTagName("head")[0];
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = path;
            s.id = "your-id";
            head.appendChild(s);
    }
    
    function addCSSFile(path) {
        var head = document.getElementsByTagName("head")[0];
        var s = document.createElement("style");
        s.type = "text/css";
        s.src = path;
        head.appendChild(s);
    }
    

提交回复
热议问题