adding to a BODY-onload function from within the page

Discussion in 'Javascript' started by laredotornado@zipmail.com, Sep 11, 2005.

  1. Guest

    Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to
    have my Javascript function execute from the BODY's "onload" method,
    but if there is already an onload method defined, I would like mine to
    run immediately after it. So in the code below, what JS would i need
    to add to my "myfile.inc" page so that I could guarantee this behavior?

    <!-- main page -->
    <html>
    <head>
    <script type="text/javascript">
    function foo() {
    ...
    }
    </script>
    </head>
    <body onload="foo();">
    <?php include("myfile.inc"); ?>
    </body>
    </html>

    <!-- myfile.inc -->
    <script type="text/javascript">
    function newFunction() {
    ...
    }
    // insert code here to make "newFunction" execute in the body's
    onload
    // method without cancelling the execution of the function "foo".
    </script>
    <table>
    </table>

    Thanks for your help, let me know if there is any other information I
    should include, - Dave
     
    , Sep 11, 2005
    #1
    1. Advertising

  2. RobG Guest

    wrote:
    > Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to
    > have my Javascript function execute from the BODY's "onload" method,
    > but if there is already an onload method defined, I would like mine to
    > run immediately after it. So in the code below, what JS would i need
    > to add to my "myfile.inc" page so that I could guarantee this behavior?
    >
    > <!-- main page -->
    > <html>
    > <head>
    > <script type="text/javascript">
    > function foo() {
    > ...
    > }
    > </script>
    > </head>
    > <body onload="foo();">
    > <?php include("myfile.inc"); ?>
    > </body>
    > </html>
    >
    > <!-- myfile.inc -->
    > <script type="text/javascript">
    > function newFunction() {
    > ...
    > }
    > // insert code here to make "newFunction" execute in the body's
    > onload
    > // method without cancelling the execution of the function "foo".
    > </script>
    > <table>
    > </table>
    >
    > Thanks for your help, let me know if there is any other information I
    > should include, - Dave
    >


    Try this thread. Read both RobB's and Mike Winter's posts.

    <URL:http://groups.google.co.uk/group/comp.lang.javascript/browse_frm/thread/362af59226c2fb75/446974fa1bd95688?q=add+onload+function+winter&rnum=2&hl=en#446974fa1bd95688>


    --
    Rob
     
    RobG, Sep 12, 2005
    #2
    1. Advertising

  3. wrote:
    > Hello, I am looking for a cross-browser
    > way (Firefox 1+, IE 5.5+)


    Just two browsers is hardly 'cross-browser'.

    > to have my Javascript function execute
    > from the BODY's "onload" method,


    You don't want to have the function executed by the body onload method,
    as that doesn't actually work. In many browser an onload attribute in
    the opening body tag results in an onload handler being created for the
    containing window object, and it is that handler that is executed when
    the page finishes loading. So if you are going to assign onload handlers
    with scripts it is most reliable (and cross-browser) to assign the
    handler to window.onload.

    > but if there is already an onload method defined,
    > I would like mine to run immediately after it.


    That is a much more complex requirement. Experimenting with the problem
    of attaching an indefinite number of functions to one onload handler I
    wrote the following function (this is the fully commented version):-

    /**
    *
    * Title: Initializer.
    * Description: Common Onload initialisation interface.
    * Copyright: Richard Cornford 2004
    * @author Richard Cornford
    * @version 1.0
    *
    */
    /**
    * A global function named - initializeMe - is created that can be used
    * to arrange the execution of an arbitrary number (but probably
    * implementation limited to the order of about 1500) of functions from
    * the - onload - handler of a web page. The intention being to allow an
    * indefinite number of other scripts to use a common interface for
    * triggering their onload initialisation functions without having to
    * worry about conflicts in the use of the onload handler.
    *
    * NOTE: This function must be included before any code that attempts
    * to use it.
    *
    * The - initializeMe - function is called with a reference to a
    * function object as its first argument, and up to 4 optional
    * additional arguments:-
    *
    * initializeMe(functRef, "idOfElement", "nameOfForm");
    *
    * - The function reference and any additional arguments are stored in a
    * function stack, the base of which is assigned as to window.onload
    * handler (or using W3C DOM addEventListener or IE attachEven, if
    * available) and when the onload event is triggered the execution of
    * the base of the function stack results in the execution of the
    * function passed as the first argument, followed by the next function
    * in the stack (which executes its function argument, And so on until
    * the stack is excused. The execution of functions passed to the -
    * initializeMe - function is in the order in which they are passed to
    * the - initializeMe - function (first in, first executed).
    *
    * The function object passed as - funcRef - is called with its first
    * argument being the (onload) - event - object and the values
    * originally passed to the call to - initializeMe - as the optional 2nd
    * to 5th arguments as its 2nd to 5th arguments (in the same order). So,
    * in the example call to - initializeMe - above, the function object
    * passed by reference as the first argument would have the pattern:-
    *
    * function(event, idString, nameString){
    * ...
    * }
    *
    * - and the two string arguments passed to - initializeMe - would be
    * passed on when it was called during the onload event.
    *
    * Note: The - event - object passed to the calls to the - funcRef -
    * functions is browser normalised with - (ev?ev:global.event) - prior
    * to the call to the function, so these function do not have to
    * normalise the event objects themselves, but they also cannot make
    * decisions about the DOM in use from inferences about their - event -
    * argument.
    *
    * @param Function Reference <code>funcRef</code>
    * @param Any (Reference or Value) <code>arg1</code> - Optional.
    * @param Any (Reference or Value) <code>arg2</code> - Optional.
    * @param Any (Reference or Value) <code>arg3</code> - Optional.
    * @param Any (Reference or Value) <code>arg4</code> - Optional.
    */
    var initializeMe = (function(){
    /* Initialise the - global - variable to be a reference to the
    global object by assigning the - this - reference to it (as
    it refers to the global object within the body of a function
    expression executed inline in a global execution context:-
    */
    var global = this;
    /* Declare a - base - variable to be a private static reference to
    the base of the function stack:-
    */
    var base = null;
    /* Set a flag to indicate whether the system is using - attachEvent
    - or - addEventListener - (which cannot be accidentally
    re-assigned) or the - window.onload - property (which can). The
    flag is set to true if either of the event attaching/listening
    method is used and left as false if - window.onload - is used
    because additional care must be taken with that option. It is
    defaulted to - false - so one of the method of associating the
    function stack base with the onload event is executed at least
    once:-
    */
    var safe = false;
    /* Test the environment to see if it supports either -
    addEventListener - or - attachEvent - on the global object and
    assign a numeric value based on the result. The numbers 2 and 3
    are used instead of 1 and 2 to avoid the
    NetFront 4/Web Browser 2.0 (ECMAScript implementation) bug in
    the handling of the logical OR and AND operations which
    erroneously results in a boolean value from the expression
    instead of a number. Boolean true would type-convert to numeric
    1 in the - switch - statement and NetFront 4/Web Browser 2.0
    would attempt to use - addEventListener -, which it doesn't
    support. Instead an erroneous boolean value in - listenerType -
    will result in the - default - branch being taken in the -
    switch - statement, which would be correct (at least much
    safer):-
    */
    var listenerType = (global.addEventListener && 2)||
    (global.attachEvent && 3)|| 0;
    /* The - getStackFunc - function returns a function object that is
    used to construct the stack of function object which are
    executed when the - onload - event occurs. the returned function
    object acts as a storage object for the - funcRef - and optional
    arguments parameters because it forms a closure when it returns
    its inner function. The function object returned has a public
    method called - addItem - which is used to link function objects
    of this type together into a stack:-
    */
    function getStackFunc(funcRef, arg1,arg2,arg3,arg4){
    /* The local variable - next - is preserved in the closure
    formed by retrying the inner function and is used to refer
    to the next function object in the stack, as set by
    - l.addItem -:-
    */
    var next = null;
    /* This inner function declaration produces the function object
    from which the stack of functions is constructed. The first
    one returned from - getStackFunc - is assigned to the - base
    - variable and also assigned as the - onload - event
    handler. As a result it is executed - onload - , at which
    point it calls the - funcRef - function (passing on the -
    event - and the optional arguments) and then calls the next
    similar function object in the stack as - next(ev) - (if
    there is one):-
    */
    function l(ev){
    /* Call the - funcRef - function (the unqualified
    identifier is resolved as the outer function's parameter
    - funcRef -, referring to the function object passed to
    the call to - getStackFunc - and preserved in the closure
    resulting from the assignment of the inner function.

    The - event - object is normalised by using -
    global.event - if no - ev - argument has been provided by
    the event handler call. and the 4 optional additional
    arguments, also stored in the closure, are passed on:-
    */
    funcRef((ev?ev:global.event), arg1,arg2,arg3,arg4);
    /* If the - next - function object is non-null call it,
    assigning the result (should be null) to - next - so
    that used function object if free to be garbage
    collected:-
    */
    if(next)next = next(ev);
    /* Null - funcRef -, the arguemnts and return null:-
    */
    return (arg1 = arg2 = arg3 = arg4 = funcRef = null);
    };
    /* Assign a function as an - addItem - method of the function
    object. This method is used to form the stack by assigning
    reference to other function object to the - next - property
    of the last function in the stack.

    An instance of the function object returned from a call to -
    getStackFunc - is passed to the - addItem - method as its -
    d - parameter:-
    */
    l.addItem = function(d){
    if(next){
    /* If - next - is non-null pass - d - on to that
    function:-
    */
    next.addItem(d);
    }else{
    /* Else assign - d - to - next -:-
    */
    next = d;
    }
    };
    /* Return the inner function object with its - addItem -
    method, forming the closure that preserves the values passed
    to - getStackFunc - as its arguments when called:-
    */
    return l;
    };
    /* The inline execution of the outermost function expression
    returns the function object that results from this function
    expression. It is that function object that is assigned to the
    global - initializeMe - variable and is the function that is
    called when - initializeMe( ... ) - is used:-
    */
    return (function(funcRef, arg1,arg2,arg3,arg4){
    /* Set-up, or extend, the function stack:-
    */
    if(base){
    /* If - base - is non-null create a new function object
    with a call to - getStackFunc - and add that function
    object to the stack by passing it as an argument to -
    base.addItem -. It will be appended on the stack:-
    */
    base.addItem(
    getStackFunc(funcRef, arg1,arg2,arg3,arg4)
    );
    }else{
    /* Else - base - is still null and a new function object is
    created with a call to - getStackFunc - and it is
    assigned to - base - as the first function in the
    stack:-
    */
    base = getStackFunc(funcRef, arg1,arg2,arg3,arg4);
    }
    /* If - addEventListener - or - attachEvent - have been used
    then - safe - will be true and no additional action is
    needed:-
    */
    if(!safe){
    /* The - listenerType - variable will be 2,3 or 0 (or
    erroneously boolean). 2 will result in the use of -
    addEventListener - and 3 in the use of - attachEvent -,
    all other values will use - window.onload - (window -
    and - global - refer to the same object).
    */
    switch(listenerType){
    case 2:
    global.addEventListener("load", base, false);
    /* When - addEventListener - has been used once the
    process does not need to be repeated as no other
    code is in a position to pass - base - as an
    argument to - removeEventListener -, so - safe -
    is set to true to flag that fact:-
    */
    safe = true;
    break;
    case 3:
    global.attachEvent("onload", base);
    /* When - attachEvent - has been used once the
    process does not need to be repeated as no other
    code is in a position to pass - base - as an
    argument to - detachEvent -, so - safe - is set
    to true to flag that fact:-
    */
    safe = true;
    break;
    default:
    /* If - base - has already been assigned to the -
    global.onload - property there is no need to do
    so again:-
    */
    if(global.onload != base){
    /* In the event of the - global.onload -
    handler existing but not being a reference
    to - base - it would be a good idea to
    preserve it by adding it to the stack:-
    */
    if(global.onload){
    base.addItem(getStackFunc(global.onload));
    }
    /* Assign the - base - function object as the
    onload event handler:-
    */
    global.onload = base;
    }
    break;
    }
    }
    });
    })();
    //^^ : The inline execution of the outermost function expresion.

    > So in the code below, what JS would i need to add to
    > my "myfile.inc" page so that I could guarantee this
    > behavior?
    >
    > <!-- main page -->
    > <html>
    > <head>
    > <script type="text/javascript">


    You would define the above function here (minus the extensive comments),
    or import it with an external JS file from a SCRIPT element in the HEAD
    section of this page (prior to this point).

    > function foo() {
    > ...
    > }
    > </script>
    > </head>
    > <body onload="foo();">
    > <?php include("myfile.inc"); ?>
    > </body>
    > </html>
    >
    > <!-- myfile.inc -->
    > <script type="text/javascript">
    > function newFunction() {
    > ...
    > }
    > // insert code here to make "newFunction"
    > // execute in the body's onload method without
    > // cancelling the execution of the function "foo".


    And call the above function as:-

    initializeMe(newFunction);

    - here. The other function - foo - could also be attached to the onload
    event in the same way, making the body onload attribute redundant.

    Obviously there are many other ways of achieving the same, especially if
    you don't expect much browser support out of the results.

    <snip>

    Richard.
     
    Richard Cornford, Sep 12, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. UJ
    Replies:
    4
    Views:
    9,697
    =?Utf-8?B?U3JlZWppdGggUmFt?=
    Jul 19, 2005
  2. Jason
    Replies:
    4
    Views:
    1,665
    Jason
    May 7, 2007
  3. David Otton

    window.onload and body.onload differences

    David Otton, Nov 4, 2004, in forum: Javascript
    Replies:
    2
    Views:
    599
    Martin Honnen
    Nov 4, 2004
  4. lwhitb1
    Replies:
    1
    Views:
    118
    Evertjan.
    Nov 22, 2005
  5. lwhitb1
    Replies:
    1
    Views:
    253
Loading...

Share This Page