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

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

    You would need to manually track this and make sure. UweB's suggestion would also work.

    You could also check out Require.js which could help you to organize your files.

    0 讨论(0)
  • 2020-12-15 19:10

    Don't include them twice. It's you who's doing the includes, after all.

    If you're doing those inclusions dynamically, though, you may check whether some global function or object has been set by the script. For example, if I have the script below in a file:

    Foo = function () {};
    

    And then I include it like this:

    <script src="../foo.js"></script>
    

    Before that script tag is parsed by the browser, Foo is undefined. After the tag is processed, Foo is a Function. You could use some logic based on that to determine whether you should include some file or not.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-15 19:13

    Not using any framework (that I know of), you can only do so by checking if a certain variable in the global scope has already been declared.

    You could declare a variable var include1 = true; inside include1.js, and do something like

    if (window.include1 !== true) {
        // load file dynamically
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题