Check if Javascript script exists on page

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

    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);
    

提交回复
热议问题