Reputation: 8065
I have a script that asynchronously loads image src
from XML file.
The sources are later assigned to the background
of a div
, and background
s change every 5 seconds.
It works well, but I want to pre-load the actual images to display already loaded image.
I do this by iterating an array, creating an img
for each source:
for(var i=0; i < clientLogos.lenght; i++){
var imgHolder = document.createElements("IMG");
imgHolder.src = clientLogos[i];
}
It's hard to tell the difference if it has been preloaded in development stage, so my question is: If I delete or over-write the variable containing the element I just created, does the element stay in DOM, or does it get deleted as well?
I'm pretty sure it stays, but I want to ask the more experienced developers.
I got confused with it:
Does document.createElement()
inserts it in the DOM or not?
Upvotes: 2
Views: 211
Reputation: 4402
In your given example element will be freed when its reference count will drop to 0. Have to perform appendChild
or such before writing to that variable to prevent it.
var imgHolder;
imgHolder = document.createElement("IMG"); // creates and references new Image
imgHolder.src = 'hello.jpg'; // some manip
/* have to save object here by means of inserting into DOM or merely pushing into array */
/* failure to do so tells JS's garbage collector what old object no longer needed */
imgHolder = document.createElement("IMG"); // deletes old image referenced by variable, creates and refs new one
Upvotes: 1
Reputation: 5061
it will be lost. the only way to access it is by assigning the same to some new variable and delete the DOM variable that holds it value.
Upvotes: 2
Reputation: 236102
Yes. The newly created element will stay in the DOM unless you explicitly remove it or you overwrite the .innerHTML
property of some parent node.
when deleting ("nulling") imgHolder
you are only deleting a reference to that node.
Upvotes: 3