How can I check if a JS file has been included already?

前端 未结 5 2057
日久生厌
日久生厌 2020-12-15 18:24

I have split my javascript in different files. I want to prevent, that javascript files are loaded twice. How can I do that?

5条回答
  •  清歌不尽
    2020-12-15 19:26

    Here's a test to see if a script has been included based on the path to the js file:

    function isScriptAlreadyIncluded(src){
        var scripts = document.getElementsByTagName("script");
        for(var i = 0; i < scripts.length; i++) 
           if(scripts[i].getAttribute('src') == src) return true;
        return false;
    }
    

    It will work for all scripts not loaded through AJAX, though you may want to modify it if you have jsonp code running.

提交回复
热议问题