0

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?

4
  • What is the value of src? is it '' or is the field actually undefined? Commented May 19, 2010 at 11:21
  • It is "", not undefined. Commented May 19, 2010 at 11:25
  • What browser is this happening in, and does it work in others? Commented May 19, 2010 at 11:50
  • Problem is that browser loads script asynchronously and the rest of the dependent code continues to execute before the script is loaded completely. I need to halt the code execution until the script is loaded, or to force synchronous script loading... Any ideas? Commented May 19, 2010 at 13:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.