Check if Javascript script exists on page

后端 未结 7 732
深忆病人
深忆病人 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:40

    Just check the selector length. Here's an example using jQuery:

    if ($('script[src="http://xxx.co.uk/xxx/script.js"]').length > 0) {
        //script exists
    }
    
    0 讨论(0)
  • 2021-02-02 10:49

    You can place id attributes on your script tags and use document.getElementById('your-id') to identify whether the script is on the page before adding.

    if (!document.getElementById('your-id')) {
        // append your script to the document here, ensure it has its id attribute set to 'your-id'
    }
    
    0 讨论(0)
  • 2021-02-02 10:50

    if you create a variable in the global scope (window.yourVariable) and check if that exists already then you can decide if you want to add your jsCode snippet code or run whatever you are running in script.js

    0 讨论(0)
  • 2021-02-02 10:53
    if (document.getElementById('element-id')) {
    // if exist must do something }
    

    hi, this is worked for me, plesea try it if you still need it

    0 讨论(0)
  • 2021-02-02 10:54

    Solution with ES6, no jQuery:

    const url = 'http://xxx.co.uk/xxx/script.js';
    
    function scriptExists(url) {
      return document.querySelectorAll(`script[src="${url}"]`).length > 0;
    }
    
    if(scriptExists(url){
      ...
    }
    

    It's not recommended to inline JS into HTML. Instead add event listeners:

     function bookmark() {
       if(scriptExists(url){
         ...
       }
     }
    
     document.querySelectorAll('a.bookmark').addEventListener('click', 
     bookmark, false);
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题