javascript img src

February 11, 2008

People keep searching for “javascript img src” … maybe this is what they’re looking for:

How to create an image DOM element dynamically and place it on the page

There are many ways of doing this, here’s one in a code snippet:

<body onload="LoadImage();">

<div id="ImageContainer">
An image will go here:<br />

<script type="text/javascript">

function LoadImage() {
	// get a reference to the DIV into which we want to put the image [1]
	var container = document.getElementById("ImageContainer");

	// create a new image element [2]
	var anImage = document.createElement("IMG");

	// when the image is loaded, attach this image element to the container DIV
	// (but not earlier) [3]
	anImage.onload = function() {

	// set the image to load [4]
	anImage.src = "";



What’s going on:

  • When the page is done loading, a JavaScript function to load the image is called.
  • [1] This functions gets an object reference to the DOM node of the DIV container to hold the image when it’s loaded.
  • [2] It then creates a new Image element DOM node, that is not yet part of the page’s node tree (and therefore does not get displayed).
  • [3] The onload handler for that node is created as a function that simply attaches the loaded image to the container. Note that this is essentially asynchronous programming: This function does not get executed until the image has been completely loaded (which may be never!). This function also uses what is called a closure over the variable context as it was defined when the function was created, meaning that all the variables outside of it’s function body are available inside, for example container.
  • [4] (Almost) as soon as an image URL is assigned to the image, the browser begins loading it.

The function defined in [3] will always execute after [4].


One Response to “javascript img src”

  1. Ron Says:

    Hi TJ.

    Your code works great for images, but I was wondering if it could do the same for an HTML page (specifically on an tag).

    Thanks for all your help.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: