Question

We had a "utility" js function that was included in several js files in our site, so to reduce code repetition we moved it to a utilities file and modified all the js files to load it before using it with getScript. This worked in most cases, but with one piece of code that uses livequery I'm getting errors.

The code that I am using successfully wherever we need to use the new function:

$.getScript("js/utilities.js", function(){
   ... use parseQueryString function ....
});

Code before:

$('.preview')
    .livequery(function(){
            $(this).attr('rel','myPage.cfm?' + parseQueryString($(this).attr('rel')));
        });

Basically, whenever an element with a class of "preview" shows up on the scene, we want to parse the rel attribute and replace it with the newly parsed string.

Code after:

$('.preview')
    .livequery(function(){
            var preview = $(this);
            // load utilities.js so that we can access the parseQueryString function
            $.getScript("js/utilities.js", function(){
                preview.attr('rel','myPage.cfm?' + parseQueryString(preview.attr('rel')));
            });
        })

The problem is, this seems to be continuing to the next iteration of the $('.preview').livequery loop before executing the callback of the getScript call. So the preview variable gets reset before we can replace its rel attribute with the appropriate value. How can I get this to execute correctly?

Was it helpful?

Solution 2

A work-around I just came up with that seems to be working... Put the getScript call around the livequery loop:

 // load utilities.js so that we can access the parseQueryString function
$.getScript("js/utilities.js", function(){
    $('.preview')
        .livequery(function(){
            $(this).attr('rel','myPage.cfm?' + parseQueryString($(this).attr('rel')));
        })
});

OTHER TIPS

I think you named the problem in your title :) 'asynchronous' is exactly the cause - loading the utility is on and since the request will be made and execution will move on meanwhile..entering yet another livequery callback if more matches are available. Frankly I think it's really bad idea to put a script loading inside a function that will be looped multiple times - it's just somewhat pointless. I see no reason not to just include it like a normal script:

<script src="js/utilities.js" type="text/javascript"></script>

I think this is the simplest and most reasonable solution. However, if you really can't use this for some reason, either ensure local copy of the variable for the callback via context (see $.ajax context option since getScript is a $.ajax shortcut it should have it too) or try synchronous ajax...the last one is an option, but please don't really try it in this case :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top