Home‎ > ‎My Notebook‎ > ‎JavaScript Tips‎ > ‎

Image Preload

Preload the images in inyour JS script or in your <head> section.

<html>
<head>
<script type="text/javascript">
  img2=new Image();
  img2.src="landscape3.gif";
</script>
</head>

Once the page has loaded you can load the image into the control using <body onLoad="MyOnLoad()">, or the mouse over event, or whatever you need to do.

The script to load the image:

<script type="text/javascript">
  document.getElementById('myImage').src=img2.src;
</script>

Warning: If your code already uses the image then you will be loading the image twice.

<img src="landscape3.gif">

The above will load the image a second time. So in the HTML code leave the src blank or use a small place holder.

<img id="myImage" onmouseover="changeImage()" border="0" width="160" height="120" src="">


If you have an image loaded via CSS (eg a bullet or background image for a DIV) make sure you comment the code out (so its not loaded twice).

ul.sbullet {
  list-style-image: url(bullet_small.gif);
  margin: 0px 0px 0px 15px;
  padding:0px 0px 0px 0px;
  }

Make sure you comment the list-style-line out (above) and then load using this code.

<script type="text/javascript">
   document.getElementById("sbullet").style.listStyleImage="url('bullet_small.gif')";
</script>

See http://www.w3schools.com/htmldom/prop_style_liststyleimage.asp

Classes vs. ID's

The one major difference between a class and an id is that classes can be used multiple times within the same page while an Id can only be used once per page.

IDs can be used to access an element using JavaScript using document.getElementById("ul1")

For IDs

#navigation {
float:left;
}

div#navigation {
float:left;
}

For Classes

.subtitle {
color: #000000;
}

div.subtitle {
color: #000000;
}

Create a hidden class

<style type="text/css">
.hiddenPic {display:none;}
</style>


Comments