"J. J. Cale" wrote:
var src = "url(someImage.jpg)";
for(var i = 0; i < arrayDivs.length; i++)
{
myDiv.style.backgroundImage = src;
try
arrayDivs[i].style.backgroundImage = 'url('+src+')';
oops
I meant arrayDivs[i].style.background = 'url('+src+')';
How do you suppose concatenating 3 strings each pass through the loop is going
to be faster than assigning a fixed string? And assigning the -background- style
rather than -backgroundImage-, the user agent probably has to do more work to
determine what aspect of the -background- style is being set. About the only
thing the OP can do to speed up the loop is to do this:
var ii = arrayDivs.length;
while (ii--) {
// I'm assuming the OP meant each array element
// is a <div>
arrayDivs[ii].style.backgroundImage = src;
}
Note that the speed difference will not be significant, he would have to loop
through arrayDivs about 1000 times to produce a noticable effect.
<div></div><div></div>
<div></div><div></div>
<div></div><div></div>
<div></div><div></div>
<div></div><div></div>
<script type="text/javascript">
var src = '';
var arrayDivs = document.getElementsByTagName('div');
var start = (new Date()).valueOf();
for (var jj = 0; jj < 1000; ++jj) {
var ii = arrayDivs.length;
while (ii--) {
arrayDivs[ii].style.backgroundImage = src;
}
}
document.write(((new Date()).valueOf() - start) + '<br>');
var start = (new Date()).valueOf();
for (var jj = 0; jj < 1000; ++jj) {
for (var ii = 0; ii < arrayDivs.length; ++ii) {
arrayDivs[ii].style.backgroundImage = src;
}
}
document.write(((new Date()).valueOf() - start) + '<br>');
</script>
IE 6.0.2800: 1125 and 1265
Firefox 1.0: 1469 and 1750
Opera 7.54: 78 and 125
Most of the speed savings are because -arrayDivs.length- is not accessed on each
pass through the loop. Ultimately, this time savings is completely overshadowed
by the fact that setting the -backgroundImage- style requires the browser to do
a GET against the http server and retrieve the image (the browser has to
download the image at least once).
--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ -
http://jibbering.com/faq