473,803 Members | 3,758 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

document.onload and getElementById( ) don't cooperate

Hi group,

I stumbled on something strange.

I simplified the problem to this:

A straightforward page with some JS:

<span id="testid">
Hi
</span>

<script type="text/javascript">
function alertID(){
var someID = document.getEle mentById("testi d");
alert (someID);
}

// call it after loading
document.onload = alertID();
</script>

will produce an alert saying [object]
as expected.
But if I 'program' the function before the span, like this, it produces
null.

<script type="text/javascript">
function alertID(){
var someID = document.getEle mentById("testi d");
alert (someID);
}
// call it after loading
document.onload = alertID();
</script>

<span id="testid">
Hi
</span>
That came as a surprise to me because I was thinking (and hoping) the
function would be evaluated AFTER the page loads.
It seems that JS is trying the function, then NOT finds the div (because it
is not on the page yet), and gives me null back, instead of evaluating the
function AFTER loading the page.

I have this behaviour on IE6 and Firefox.

Can anybody shed some light on this?

Regards,
Erwin Moller
Jan 5 '06
11 42829
Michael Winter wrote:
On 05/01/2006 16:15, Erwin Moller wrote:

[snip]
defer delays execution of the script untill body content is parsed and
rendered.
No, it doesn't. The defer attribute /hints/ that execution can be
delayed. It makes no promises about when, or even that a delay will occur.

Though waiting until the markup had been parsed would be sensible,
waiting until rendering has been performed is probably not.

Ok, don't blame me, I was just repeating what I read here:
http://www.websiteoptimization.com/speed/tweak/defer/

<quote>
First introduced by Internet Explorer 4, the defer attribute of the script
element is now part of the HTML 4 and XHTML specifications. The defer
attribute gives a hint to the browser that the script does not create any
content so the browser can optionally defer interpreting the script. This
can improve performance by delaying execution of scripts until after the
body content is parsed and rendered. Here's the brief paragraph describing
the defer attribute from the HTML 4.01 specification:

When set, this boolean attribute provides a hint to the user agent that
the script is not going to generate any document content (e.g., no
"document.write " in javascript) and thus, the user agent can continue
parsing and rendering.
</quote>

You are probably both right: they use the word 'may' instead of 'will',
making it all sound a lot less reliable.

Anyway, thanks for the warning.

Regards,
Erwin Moller

Mike


Jan 5 '06 #11
Erwin Moller said the following on 1/5/2006 11:32 AM:
Michael Winter wrote:

On 05/01/2006 16:15, Erwin Moller wrote:

[snip]

defer delays execution of the script untill body content is parsed and
rendered.


No, it doesn't. The defer attribute /hints/ that execution can be
delayed. It makes no promises about when, or even that a delay will occur.

Though waiting until the markup had been parsed would be sensible,
waiting until rendering has been performed is probably not.


Ok, don't blame me, I was just repeating what I read here:
http://www.websiteoptimization.com/speed/tweak/defer/

<quote>
First introduced by Internet Explorer 4, the defer attribute of the script
element is now part of the HTML 4 and XHTML specifications. The defer
attribute gives a hint to the browser


"gives a hint to the browser".......
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jan 5 '06 #12

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

Similar topics

2
1948
by: DJ WIce | last post by:
Hi, I want to resize an IFRAME. It works nicely when I try to resize the frame with a commant loaded via onfocus="if (parseInt(document.body.scrollHeight)< parseInt(document.body.offsetHeight)) parent.document.getElementById('iframeID').style.height=parseInt(this.docume nt.body.scrollHeight)+2+'px';
4
5485
by: lawrence | last post by:
Can anyone tell me why this code works in Netscape 7.1 but not in IE??? <SCRIPT type='text/javascript'> function makeVisible(nameOfDiv) { document.getElementById(nameOfDiv).style.visibility='visible'; document.getElementById(nameOfDiv).style.height='auto'; if (nameOfDiv != 'weblogs')
7
5997
by: PaulB | last post by:
Good Morning everybody, I'm trying to adapt a tutorial script that will handle the behaviour of an "Expanding/Contracting" site-navigation menu. The code that seems to handle the expansion and contraction follows at the bottom of my message here. This following line is a big part of my hang-up: document.getElementById('m1').style.display='none';
3
9278
by: davidkarlsson74 | last post by:
Error: document.getElementById("folderMenu").cells has no properties File: http://www.volkswagen.se/tillbehor/js/foldermenu.js Rad: 49 The function activates different DIV:s, but doesn't seem to work on FireFox or Netscape. What could be wrong? The function: function setActiveTab(tabNo) {
136
9461
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
2
4442
by: Earl Teigrob | last post by:
I am trying to build a custom control to wrap my smart navigation implimention (not microsofts 'cause it has problems) The follow code works fine when the onclick and onload events are defined in the Body tag. However, when I try to set them in Javascript code, I get errors. What am I doing wrong??? **********THIS WORKS ************ <html>
5
4441
by: HopfZ | last post by:
I made two shortcut functions for document.getElementById as: function EBI2(id){return document.getElementById(id)}; var EBI3 = document.getElementById; But EBI3 don't work. EBI2('myText'); //works EBI3('myText'); //unexpected error
6
4625
by: linuxnooby | last post by:
Hi I want a form field to be selected when the page loads. But I get the error message Error: document.getElementById("ff") has no properties any ideas what I am doing wrong? code below
4
2647
by: dr1ft3r | last post by:
Hey guys, I'm building a site for a landscaping business down the street and can't seem to get part of the code functioning correctly. The code fails on line 68 where I make a reference to an iframe's src property. Being that IE does not follow standard and considers an id, name, etc as a qualifying identifier for the document.getElementById object, I double checked to make sure that there's only one instance of id = "servif" and I never use...
0
9700
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
9564
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,...
0
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10292
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
10068
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
9121
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
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.