Tips for binding multiple JavaScript functions to the OnLoad event handler

Source: Internet
Author: User

One, the OnLoad event occurs condition

The user enters the page and all elements of the page are loaded. If you add a JavaScript function at the initial position of the page, the DOM is incomplete because the document is not loaded, which can cause the function to execute incorrectly or not achieve the effect we want.

Two, bind multiple functions to the OnLoad event

1, first show a wrong approach

1 window.onload = firstfunction; 2 window.onload = secondfunction;

During the actual execution, only the last function is executed, because each event handler can only bind one instruction.

2, use an anonymous function

1 function ()2{3    firstfunction (); 4     secondfunction (); 5 }

3, a general-purpose solution

The function name is Addloadevent, which is written by Simon Willision, which is the name of the function that needs to be executed when the page finishes executing.

1 functionaddloadevent (func)2 {3     varOldonload =window.onload;4     if(typeofWindow.onload! = ' function ')5     {6Window.onload =func;7     }8     Else9     {TenWindow.onload =function() One         { A oldonload (); - func (); -         } the     } -}

The advantage of this function is that no matter how many functions need to be executed, I can just add a single statement to get it done without having to modify the previous code.

1     addloadfunction (firstfunction); 2     Addloadfunction (secondfunction);

Tips for binding multiple JavaScript functions to the OnLoad event handler

Related Article

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.