473,735 Members | 2,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding to a BODY-onload function from within the page

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 "newFunctio n" 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 '05 #1
2 7676
la***********@z ipmail.com 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 "newFunctio n" 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.c o.uk/group/comp.lang.javas cript/browse_frm/thread/362af59226c2fb7 5/446974fa1bd9568 8?q=add+onload+ function+winter &rnum=2&hl=en#4 46974fa1bd95688 >
--
Rob
Sep 11 '05 #2
la***********@z ipmail.com 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(fu nctRef, "idOfElemen t", "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 addEventListene r 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.e vent) - 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 - addEventListene r - (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 -
addEventListene r - 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 - addEventListene r -, 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.addEven tListener && 2)||
(global.attachE vent && 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(fu ncRef, 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(funcR ef, 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(fu ncRef, 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(fu ncRef, arg1,arg2,arg3, arg4);
}
/* If - addEventListene r - 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 -
addEventListene r - and 3 in the use of - attachEvent -,
all other values will use - window.onload - (window -
and - global - refer to the same object).
*/
switch(listener Type){
case 2:
global.addEvent Listener("load" , base, false);
/* When - addEventListene r - 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 - removeEventList ener -, so - safe -
is set to true to flag that fact:-
*/
safe = true;
break;
case 3:
global.attachEv ent("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.onloa d != 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.onloa d){
base.addItem(ge tStackFunc(glob al.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 "newFunctio n"
// execute in the body's onload method without
// cancelling the execution of the function "foo".


And call the above function as:-

initializeMe(ne wFunction);

- 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.
Sep 11 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1942
by: Tristan Tarrant | last post by:
Dear all, we're having a problem with the SOAP extension provided by PHP5. Similar calls using the SOAP component of PEAR work. Tracing the request with a network analyzer this is what PHP5 generates: <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="TCOL_MATRIX">
3
2113
by: mike | last post by:
I bought 3 books and spent weeks trying to add a record to my database, but haven't figured it out??? I've tried both sql and addnew method, but to no avail. Below is my sql method. Any ideas would be highly appreciative. <% @Language=VBScript %> <% Option Explicit %> <% Response.Expires = 0 %> <% Dim objConn, objRS, strQ
15
24761
by: nAmYzArC | last post by:
Hi everyone, I'm setting the body of an email using values from a form firstname = bob lastname = dole ebody = 'First Name: ' + firstname + '\r\n' + 'Last Name: ' + lastname window.location.href = 'mailto:myemail@mycompany.com?subject=test
4
3725
by: glebur | last post by:
Hi, I'm trying to create a web service client in C# but I get stuck at one of the first steps. When adding a Web reference to the Visual Studio project; I get this error (this is a translation, the English terms might not be exact) : "Error in the custom tool : Impossible to import WebService/Schema. Impossible to import binding 'cmsserverbinding' (it's the name of the binding in my WSDL file) from namesapce 'urn:cms. Impossible to...
2
3976
by: EdWhyatt | last post by:
Hi all, I hope there is someone out there who can help me out - it has to be something obvious. I am simulating mail traffic, and want to include multiple attachments to my mail. I have created a temporary array containing a number of files - for now just 2. Debugging my code, I can see that I am correctly storing the files in the array, and then 1 by 1 adding one file at a time to the message header.
5
1875
by: yawnmoth | last post by:
I'm having some difficulty with adding elements to a webpage via the DOM. The following works: main.htm: <script> js = document.createElement('script'); js.src='test.js'; document.getElementsByTagName('head').appendChild(js); </script>
1
3013
by: iwdu15 | last post by:
ok, this is driving me insane, plz someone help. im attempting to add text to a webbrowser document text by doing as follows, IM is an Instant Message object in the AIM SDK, the line Dim str As String = IM.GetConvertedText(decode) get the text in the im, which works perfectly fine, ive tested it. all my variables have a value
7
19843
by: Jayyde | last post by:
Can anyone point me to a good guide for how to do this or give me some pointers? What I'm basically trying to do is use the Web Browser as a picture box that has a web source for the image, but it doesn't have a click event for the control (so I can pop up a new window with an enlarged image). I can put a panel above it (on a user control) with a click event or even a picture box, but Transparent background apparently isn't actually...
4
1309
by: Christo | last post by:
novice with mysql so be slow. Want to be able to update the contents of a database row through a form, i want to be able to load the contents of a specific row my database table is as follows id(pk) | title | body | date(text field) --------------------------------------------------------------------------- 1 | hello | test | 15-11-2006 13:44
0
1144
by: Vids | last post by:
Hi, We are doing migration of web service from VS2003 to VS2005 After upgrading the project I m trying to add a web reference to the web service. While adding web reference it shows all the web methods inside that web service but it show the message in the right "There was an error downloading 'http://localhost/MyWebSite/WebServices/Journal.asmx'. The request failed with the error message: -- <html><head><title>Object...
0
8959
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8784
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9199
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8199
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6049
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4821
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.