Free Bud
Free Bud

Reputation: 766

JavaScript function sometimes called, sometimes not

This looks weird... I have an HTML page in which I can't modify the "body" line (because it's php-included from another file). In the file, before the closing "/body" tag, I have a JavaScript function:

<script language="JavaScript">
function doSomething () {
  /* some code */
}
</script>

Since I want this function to be executed when the page is displayed, and since I can't modify the "body" line, I added somewhere a small image, and called this function when it loads:

<img src="transp.gif" border="0" width="0" height="0" onload="doSomething();" />

Problem is the function is sometimes called and sometimes not called. I even verified this with appropriate "alert" statement... What am I doing wrong? Why isn't the "onload" executing consistently?

Upvotes: 0

Views: 3421

Answers (3)

code4coffee
code4coffee

Reputation: 677

Have you tried the following?

<html>
<body>
<script type="text/javascript">
window.onload = function () {
//your code here
}
</script>
</body>
</html>

Upvotes: 2

Mackan
Mackan

Reputation: 6271

Problem is that you try to call the function before it's in the DOM. Call "DoSomething" after the function is loaded...

<script language="JavaScript">
function doSomething () {
  /* some code */
}
doSomething();
</script>

But the cleanest solution would be to use:

<script>
window.onload=function(){
   /* some code */
};
</script>

Upvotes: 3

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

you can use event window.load that fired when the page (and your img) is loaded

<script>
window.onload = function(){
   //code
};
</script>

and your img without event

<img src="transp.gif" border="0" width="0" height="0" />

Upvotes: 3

Related Questions