tags:

views:

47

answers:

1

Hi there,

I have a problem with dynamically added script element (using jQuery). Code for adding new script element to DOM is this:

var pScript = document.createElement("script");
pScript.type = "text/javascript";
pScript.src = sFile;


// Add element to the end of head element
$("head").append(pScript);

The script is added with no problem, and the code runs perfectly.

But, the problem occurs when I try to find the newly added script. I use this code to iterate through all script elements:

var bAdd = true;
$("script").each(function()
{
  if(this.src == sFile)
    bAdd = false;
});

(I need this code to prevent adding script that is already loaded)

Problem is that all other script elements have src attribute set, but the newly added (dynamically) has not...

Any idea?

+1  A: 

If the src is in fact empty (due to some security measure or something) then you can try something else like

var include = (function() {
    var included = {};
    return function(url) {
        if (!url in included){
            //include script
            ...
            included[url] = true // you can set it to anything
        }
    };
})();

UPDATED the code to not contaminate the scope with included.

Sean Kinsey
Yes, that's my alternative if we don't fix the current method :)
Stazh
I've decided to go with your solution. It works perfectly and it's easy to implement. Thanks a lot!
Stazh