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?
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')));
})
});