Would using document.getElementById(id).appendChild(img)
in the following code cause problems for the browser? I'm wondering if I use appendChild() to update an image many times during the lifetime of a document might create memory issues or would only one node be created?
I know that the following code only loads the image once but I was planning on expanding the code to randomly change the image as an animation. The document would see the call for
document.getElementById(id).appendChild(img)
many times during the life of the document.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var img = document.createElement("IMG");
images = new Array();
function random_image(id)
{
var i = 0;
for(i = 0; i < 7; i++)
{
images[i] = "image" + i + ".jpg"
}
var random = (Math.floor(Math.random()*7));
img.src = images[random];
document.getElementById(id).appendChild(img);
}
</script>
</head>
<body onload = "random_image('image')">
<div id="image"></div>
</body>
</html>
If you're doing it as an animation, you're better off just changing the src of the image tag w/ the appropriate image url rather than replacing the image tag itself.
* Edit in response to the first comment *
You already have the code you need, but what you're doing is re-appending the image to the document every time. What I'm suggesting is to just change the src of the image you've already got.
var img = document.createElement("IMG");
images = new Array();
var i = 0;
for(i = 0; i < 7; i++){
images[i] = "image" + i + ".jpg"
}
function onLoad(){
random_image('image');
document.getElementById(id).appendChild(img);
}
function random_image(id){
var random = (Math.floor(Math.random()*7));
img.src = images[random];
}
window.onload = onLoad;
Note that I'm sort of assuming that the document load evnet isn't the only time you're calling the function. If it were, then your question is moot b/c you're asking about the impact of calling it a lot. Doing it the way I'm showing, you first off get the code out of the document (a good thing) and also make it so that any calling code can replace the image file sourced by that one image tag.