JS executes multiple window.onload produce too much recursion error resolution

Source: Internet
Author: User

, the common solution is as follows:

The code is as follows Copy Code

<script type= "Text/javascript" >
var func = window.onload;
Window.onload = function () {
Func? Func (): 0;
Alert (1);
}
</script>

The principle is to pass the Window.onload event one level at a time to ensure that every window.onload event can be executed, but if there are multiple calls and variable names, it will produce too much recursion error, as follows

The code is as follows Copy Code

<script type= "Text/javascript" >
var func = window.onload;
Window.onload = function () {
Func? Func (): 0;
Alert (1);
}

func = window.onload;
Window.onload = function () {
Func? Func (): 0;
Alert (2);
}
</script>

The above implementation executes two window.onload events, but because each pass window.onload event is defined as the same variable name, a too much recursion error is generated.

Solving method
The reason for this is that the definition of the same variable name produces loop execution code, so the solution needs to be resolved only by defining the variable name differently. As follows

The code is as follows Copy Code

<script type= "Text/javascript" >
var func = window.onload;
Window.onload = function () {
Func? Func (): 0;
Alert (1);
}

func1 = window.onload;
Window.onload = function () {
Func1? Func1 (): 0;
Alert (2);
}
</script>


If a Web page appears multiple Window.onload events, try to merge operations processing, or implement a jquery-like ready event mechanism to solve redundant code problems and improve the readability of your code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.