Science Library - free educational site

JavaScript Techniques

Normally, when a JS script is included via HTML, the browser stops until it has interpreted the script, and only then does it continue with the rest of the HTML file.

This may slow the loading of the page enough for the user to be inconvenienced, especially if the script in question is very large or includes long and involved operations.

A first 'trick' to improve the perception of the page's loading time is to include the script at the end of <body> rather than in the <head>.

This permits most pages to load prior to starting to run the script.

<html> 
    <head> 
        <title>Example</title> 

        <script src="http://www.zumguy.com/example.js" 
language="javascript" type="text/javascript"> 
        <!-- this tag presents a blank page to the user 
until the script has finished executing --> 
    </head> 
    <body> 
        <!-- page content... --> 

        <script src="http://www.zumguy.com/example.js" 
language="javascript" type="text/javascript"></script> 
        <!-- here, instead, most of the page has already loaded, 
and the user may start to read it --> 
    </body> 
</html> 

Another method is via JavaScript itself. This is very useful because it loads a script only if needed. However, some precautions must be employed.

IThe reason that browsers block in order to run scripts is to avoid situations of conflict between two scripts (race conditions), where one script executes before (or simultaneously) another, potentially causing errors. This fact must be borne in mind when using this technique.

To load another script via JavaScript, we will use a function to create a tag <script> and include it in the HTML page:

var loadScript = function(fileName, callback) {
    var scriptTag = document.createElement("script");
    scriptTag.src = fileName;
    
    if (callback) {
        scriptTag.onload = callback;
        scriptTag.onreadystatechange = function() {
            if (scriptTag.readyState == 4) {
                callback();
            }
        }
    }
    
    document.getElementsByTagName("head")[0].appendChild(scriptTag);
}

We create a function called loadScript which takes two arguments: a string containing the address of the file to be loaded (mandatory) and a function (optional) to execute as soon as the script has loaded and executed.

The first thing the function does is create an HTML element <script> with the file address as source. After this, if a function has been supplied as a second argument, it is assigned to the onload property of the tag. Finally, the script is included at the end of the <head> element of our HTML file.

Therefore, if we have, for example, two large scripts, and we have to decide with JavaScript which to execute, we can save the time it takes to load the second file for no purpose:

if (condition == True) {
    loadScript("script1.js");
} else {
    loadScript("script2.js");
}

Simple, but effective!

Preload

If a webpage contains a lot of images of a bulky size, despite the rapid download rates of broadband, there are a number of good reasons to manage their download. A basic technique is preloading hidden images so they are ready for the application which is launched by the user. An example of this would be a slideshow.

The preloading of images can be achieved using JavaScript. The concept is very simple: the basic page loads first, and unnecessary or initially hidden images, such as later images of slideshows are loaded into the browser cache in the background, without the user needing to do anything.

This avoids delays which would occur if the page only downloads the images at the time they are called by the browser to load.

Used well, this technique can also avoid multiple loadings of bulky items. The cache retains the downloaded items, even when the page is left, and makes them available when the visitor returns to the page. Good web design aims to enhance the experience of the user as much as possible, and this is a technique which aids in achieving that objective.

Furthermore, in some cases, the preloading of images is essential for the proper function of the page, as we shall now see.

// URL of the image to download

var src = 'http://www.example.com/image.jpg';

// new image object

var img = new Image();

//the download method will be executed once the image has been completely downloaded

img.onload = function () { alert("Image downloaded!"); };

//the onError method will be executed if there is a download error

img.onerror = function () { alert("Error!"); };

// we assign the already specified URL. Now the image can be loaded

img.src = src;

Example: preloading a list of images

Usually, however, more than a single image is loaded. To load a list of images we run the following script:

preload function (src) { // src is the URL of the image to load

var img = new Image();

img.onload = function () { alert("Image loaded!"); };

img.onerror = function () { alert("Error!"); };

img.src = src;

}

// list of images to load

var urls = ['http://www.example.com/image1.jpg',

'http://www.example.com/image2.jpg',

'http://www.example.com/image3.jpg',

'http://www.example.com/image4.jpg'];

// load all images in the list

var L = urls.length;

for (var i = 0; i < L; i++) {

preload(urls[i]);

}

Here we have put the code to preload the images in a function called preload. Then we use a loop to call that function for each element in the image list.

Content © Renewable.Media. All rights reserved. Created : March 2, 2014 Last updated :March 7, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Environment

Environmental Science is the most important of all sciences. As the world enters a phase of climate change, unprecedented biodiversity loss, pollution and human population growth, the management of our environment is vital for our futures. Learn about Environmental Science on ScienceLibrary.info.

Environmental Science

Great Scientists

Werner Heisenberg

1901 - 1976

Werner Heisenberg was a German physicist, and a key member of the 'Copenhagen Interpretation', which proposed an observer-creation understanding of quantum phenomena, based on Niels Bohr's theories and Heisenberg's Uncertainty Principle.

Werner Heisenberg, 1901 - 1976. German physicist and proponent of the Heisenberg Uncertainty Principle.
IT Forum by Sean Bone

Quote of the day...

A carbon tax would be 'win-win-win-win-win' for the United States. It would reduce harmful emissions, generate funds for the deficit, weaken petro dictators, strengthen the dollar, drive clean-tech innovation, and stil leave some money to lower corporate and income taxes. However, it is entirely off the table, while self-defeating proposals are on it.

Renewable.Media Internet Promotions

Renewable energy media services