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
}
Move the
onloadOthers
andresources
variables in a new closure, by prefixing thevar
keyword.Currently, your code "recycles" these (global) variables, because they're declared in a non-local scope:
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?.