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

前端 未结 5 2063
日久生厌
日久生厌 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:10

    I have tackled this using a generic self-invoking function added at the bottom of each dynamically loaded script.

    First - by declaring a new empty array in my base file or a script that will always be loaded, ie the main page in my case index.php

    var scriptsLoaded = new Array();
    

    Then add a self executing function to the end of the loaded script:

    (function () { scriptsLoaded.push( 'this_script_name.js' ) })();
    

    With this approach any filename in the scriptsLoaded array should only refer to scripts that have been fully loaded already. Simply checking this array would indicate whether a script has been loaded which can also be used as a check for whether to execute on-load style functions for whatever the script is needed for

提交回复
热议问题