Check if Javascript script exists on page

后端 未结 7 737
深忆病人
深忆病人 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 11:04

    You can check whether your script is loaded like this:

    function isMyScriptLoaded(url) {
        if (!url) url = "http://xxx.co.uk/xxx/script.js";
        var scripts = document.getElementsByTagName('script');
        for (var i = scripts.length; i--;) {
            if (scripts[i].src == url) return true;
        }
        return false;
    }
    

    Alternatively, you could do something like this:

    Bookmarklet
    

    This "pollutes" the global namespace with the jsCode variable, but that might be a necessary evil. You could rename it to something that is unlikely to appear in the document where the bookmarklet is run.


    Please note that while the javascript URI scheme is okay for bookmarklets as in this case, it's not considered to be a good practice for normal use.

提交回复
热议问题