Getting the “RangeError: Maximum call stack size e

2019-08-08 17:26发布

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
    }

1条回答
仙女界的扛把子
2楼-- · 2019-08-08 18:08

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?.

查看更多
登录 后发表回答