/    Sign up×
Community /Pin to ProfileBookmark

Help w/ Image preloading…

Help me, I’ve been trying to successfully preload some images using javascript … but had no luck so far… I am using :

[code=php]
var imgs = new Array(“image1.jpg”, “image2.jpg”, …);
function preloadEm() {
for (i=0; i<imgs.length; i++) new Image().src=imgs[i];
}

——
<body onLoad=”preloadEm()”>
[/code]

Do I like have to use another array to hold the images? Like :

[code=php]
var imgs = new Array(“image2.jpg”, “image2.jpg”, …);
var imgs2 = new Array();
function preloadEm() {
for (i=0; i<imgs.length; i++) {
imgs2[i] = new Image();
imgs2[i].src = imgs[i];
}
}
[/code]

Can anyone help me? Which is the right way to preload images with javascript?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@A_Tame_LionOct 07.2006 — Znupi,

The code I used, and I warn you I am a beginner is:

[CODE]<script Language="JavaScript" type="text/javascript">

image1 = new Image();
image1.src = "images/buttons/home.jpg"; <!-- filepath to image -->
image2 = new Image();
image2.src = "images/buttons/home_mo.jpg";
image3 = new Image();
image3.src = "images/buttons/blog.jpg";
image4 = new Image();
image4.src = "images/buttons/blog_mo.jpg";

</script>[/CODE]


That's in the <head></head> section. Then in the <body></body> I have:

[CODE]<a onmouseover="document.getElementById('home').src = 'images/buttons/home_mo.jpg';" onmouseout="document.getElementById('home').src = 'images/buttons/home.jpg';" border="0" href="index.html">
<img id='home' src="images/buttons/home.jpg" border="0" alt="Home"/></a>
<a onmouseover="document.getElementById('blog').src = 'images/buttons/blog_mo.jpg';" onmouseout="document.getElementById('blog').src = 'images/buttons/blog.jpg';" border="0" href="blog/?p=1">
<img id='blog' src="images/buttons/blog.jpg" border="0" alt="Blog"/></a>[/CODE]


Works for me!
×

Success!

Help @Znupi spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...