getScript - How to only call if not already called

var gotContacts = 0;
function getContacts(){
    if (!gotContacts){
        $.getScript('/javascripts/contacts.js', function() {
            gotContacts = 1;
            doSomethingWithContacts();
        });
    }else{
        doSomethingWithContacts();
    }
}

My situation was different. I used a menu to load content into a div using jquery. To prevent too many scripts from being present in the header section, I used .getscript to load the file only if that link was called. Here is the solution I came up with to prevent duplicates:

First I create a function that was responsible for loading the script. This is part of the global.js file on my site and the global.js file is hard coded into the header:

var loadedScripts=new Array();

function loadScriptFiles(scriptArray){

    if($.isArray(scriptArray)){
        $.each(scriptArray, function(intIndex, objValue){
            if($.inArray(objValue, loadedScripts) < 0){
                $.getScript(objValue, function(){
                    loadedScripts.push(objValue);
                });
            }
        });
    }
    else{
            if($.inArray(script, loadedScripts) < 0){
                $.getScript(script, function(){
                    loadedScripts.push(objValue);
                });
            }





    }
}

This takes two types of loads, either an array, or a single script value. If it's an array, it loops through each element and loads it. If it's not an array, then it'll just load one file. You'll see that part in a minute.

Important parts: See I've created an array in the global scope (outside of the function) called loadedScripts. Because this is part of the global.js file, it never gets reloaded and can be called from anywhere. But for our purposes, I simply check to see if the script name being loaded is already in the array using:

if($.inArray(objValue, loadedScripts) < 0){

Because the jquery inarray function returns -1 if the value is not found, I only continue if the value is less than 0. Anything else means the value is in the array.

Here is how you call the function to be used. Place this code anywhere (I put it at the top) of the dynamic page that will be called into play.

<script type="text/javascript">
    var scriptArray=new Array();
    scriptArray[0]="[REPLACE THIS WITH THE PATH TO THE JS FILE]";
    scriptArray[1]="[REPLACE THIS WITH THE PATH TO THE JS FILE]";
    loadScriptFiles(scriptArray);
</script>

If done properly, you'll notice it only gets loaded once.

Tags:

Jquery