badso
badso

Reputation: 109

How does onload work in Javascript?

In the book Pro HTML5 Games there is the following piece of code:

    // Load all data and images for a specific level
load:function(number){
    // declare a new currentLevel object
    game.currentLevel = { number: number, hero: [] };
    game.score = 0;
    $('#score').html('Score: '+game.score);
    var level=levels.data[number];

    //load the background, foreground, and slingshot images
    game.currentLevel.backgroundImage=loader.loadImage("images/backgrounds/"+level.background+
    ".png");
    game.currentLevel.foregroundImage=loader.loadImage("images/backgrounds/"+level.foreground+
    ".png");
    game.slingshotImage=loader.loadImage("images/slingshot.png");
    game.slingshotFrontImage =loader.loadImage("images/slingshot-front.png");

    //Call game.start() once the assets have loaded
    if(loader.loaded){
        game.start()
    } else {
        loader.onload = game.start;
    }
}

The loader object is the following:

var loader= {
loaded:true,
loadedCount:0, // Assets that have been loaded so far
totalCount:0, // Total number of assets that need to be loaded

init:function(){
    // check for sound support
    var mp3Support,oggSupport;
    var audio =document.createElement('audio');
    if (audio.canPlayType) {
        // Currently canPlayType() returns: "", "maybe" or "probably"
        mp3Support ="" != audio.canPlayType('audio/mpeg');
        oggSupport ="" != audio.canPlayType('audio/ogg; codecs="vorbis"');
    } else {
        //The audio tag is not supported
        mp3Support =false;
        oggSupport =false;
    }
    // Check for ogg, then mp3, and finally set soundFileExtn to undefined
    loader.soundFileExtn =oggSupport?".ogg":mp3Support?".mp3":undefined;
},

loadImage:function(url){
    this.totalCount++;
    this.loaded =false;
    $('#loadingscreen').show();
    var image =new Image();
    image.src =url;
    image.onload =loader.itemLoaded;
    return image;
},

soundFileExtn:".ogg",

loadSound:function(url){
    this.totalCount++;
    this.loaded =false;
    $('#loadingscreen').show();
    var audio =new Audio();
    audio.src =url +loader.soundFileExtn;
    audio.addEventListener("canplaythrough", loader.itemLoaded, false);
    return audio;
},

itemLoaded:function(){
    loader.loadedCount++;
    $('#loadingmessage').html('Loaded '+loader.loadedCount+' of '+loader.totalCount);
    if (loader.loadedCount === loader.totalCount){
        // Loader has loaded completely..
        loader.loaded=true;
        // Hide the loading screen
        $('#loadingscreen').hide();
        //and call the loader.onload method if it exists
        if(loader.onload){
            loader.onload();
            loader.onload =undefined;
        }
    }
}

I have the following questions:

1)If onload is a method, shouldn't we use it as, for example, imageThatWeWantToLoad.onload(stuff we want to do after image has been loaded), instead of imageThatWeWantToLoad.onload = (do what we want to do after image has been loaded)?

2)What does loader.onload=game.start; part does (game is an object and start is a method defined inside the game object) exactly? I think I understood that loader.onload=game.start; means that once the loader object has been loaded, game.start will be called, but since game.start is a method, shouldn't it be loader.onload=game.start(); ?

3)Also, onload means 'data received by the browser' ?

Upvotes: 0

Views: 429

Answers (4)

Raghav Simlote
Raghav Simlote

Reputation: 84

Onload in JavaScript can be described as:

  1. onload here is accessed as property and we are assigning the property with the result of the function. So function will execute and the final result will be assigned to the property. So basically calling of function and assigning the result to the property has done simultaneously in single line of code.

  2. In this case, we want to know that whether loader onload method has executed or not by checking loader.loaded property. If it has executed then call game.start() without assigning to any function to execute in sequence as onload method has executed. If it has not executed then we have assigned the game.start function to loaded.onload function so we have used them as property to assign the function to another function, so now when onload method will be called, it will now execute game.start() function as onload is replaced by game.start.

  3. Onload means that object has been loaded. We use onload event in body tag of html to know that webpage has loaded all the content and we may perform our actions now for smooth functioning.

Upvotes: 0

Amadan
Amadan

Reputation: 198486

1) image.onload is not intrinsically a method. It is just a property, just like name is a property in dog after we execute

dog = { name: null };

A property of an object is a method if it contains a function. So,

dog['bark'] = function() { console.log("Woof"); };

Now we could do dog.bark() to invoke this method.

If image.onload is a method (i.e. if it contains a function) at the time the image is loaded, it will be run by the browser. It is not a method that is meant for us to call, it is for us to define.

2) It does exactly what it looks like - assigns contents of game.start (a function) to loader.onload. Now both properties refer to the same function. If we did loader.onload = game.start(), it would execute game.start and assign the result of the execution to loader.onload; but we want to assign the function itself, so no parentheses.

Upvotes: 2

Deepak Ingole
Deepak Ingole

Reputation: 15772

  1. Loader is object and loadImage is property defined on it.

  2. The property loader.onload is a pointer to a function (anonymous)

  3. loader.onload = game.start; // makes loader.onload point to game.start. i.e saying game.start() === loader.onload();

Upvotes: 0

slebetman
slebetman

Reputation: 114014

The property loader.onload is a pointer to a function (technically it's just a plain pointer but let's ignore that for a moment).

Doing:

loader.onload = game.start;

Assigns the function game.start to the pointer loader.onload.

Then later on, in the loader code you see:

if(loader.onload){
    loader.onload();
    loader.onload =undefined;
}

It basically checks if loader.unload has been assigned anything (undefined is considered false in javascript). If it has call the function it points to then set the pointer back to undefined.

The explanation above glosses over several facts about javascript. But it's basically what's going on.

Upvotes: 3

Related Questions