1

how can i add function on top of the already existing function?

i'm using following way and it gives me error on resources.onload

    resource = document.getElementById(this.id);

    if (resource && resource.getAttribute('data-loading'))
    {           
        onloadOthers = resource.onload;
        onloadThis   = this.onComplete.bind(this);

//following line give error

        resource.onload = function () { // callback loops again and again!!!!!!
            if (typeof onloadOthers == "function")
                onloadOthers();
            onloadThis();
        };

        return; // just added another callback, no need to add it again.
    }
    else if (resource)
    {           
        this.onComplete();
        return; // already exist
    }

    if (this.type == "js")
    { //if filename is a external JavaScript file
        var code = document.createElement('script');
        code.setAttribute("type", "text/javascript");
        code.setAttribute('data-loading', 'yes');
        code.setAttribute("src", this.file);
        code.onload = this.onComplete.bind(this);
        code.onreadystatechange = code.onload; // ie fix
    }
Basit
  • 16,316
  • 31
  • 93
  • 154
  • The error usually means a never ending loop – HMR May 17 '13 at 11:55
  • yes i know that. how can i fix it? i want to add previous callback on top of new callback. so they both get triggered onload. – Basit May 17 '13 at 11:56
  • 1
    `onloadOthers` may cause infinite recursion. Make sure that the `unloadOthers` variable is contained in a new closure. – Rob W May 17 '13 at 11:56
  • @RobW i agree.. anyway to solve it? – Basit May 17 '13 at 11:57
  • 1
    @Basit Yes, put [`var`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var) before `onloadOthers` (assuming that the code you've shown is contained in `function(){` and `}`, which created a closure. Currently, your code probably "recycles" the `resource` and `onloadOthers` (global) variables. By prefixing `var`, the variables will stay in the local scope. – Rob W May 17 '13 at 11:59
  • @RobW can you write that in answer, so i can accept it. it works :) – Basit May 17 '13 at 12:02

1 Answers1

1

Move the onloadOthers and resources variables in a new closure, by prefixing the var keyword.

Currently, your code "recycles" these (global) variables, because they're declared in a non-local scope:

var onloadOthers;
function func() {
    onloadOthers = ...;
    resource.onload = function() {
        onloadOthers(); // Calls the global `onloadOthers` function.
    };
}
func(); // Defines `onloadOthers`
func(); // Overwrites `onloadOthers`

By moving the variable to a local scope, all instances of the function will have an "own" onloadOthers variable, which solves the problem.

If you want to learn more about this topic, read How do JavaScript closures work?.

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678