Problem with dynamically added script element - attribute src is empty
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?
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
.
精彩评论