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?
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?
-
1
Why not using the right onload?
window.onload = function() { doSomething() };
. – DontVoteMeDown Commented Dec 17, 2013 at 13:32 - If the image is in cache I don't think the onload is called. you are better of using one of the suggestions posted. – Fred Commented Dec 17, 2013 at 13:35
3 Answers
Reset to default 3Problem 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>
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" />
Have you tried the following?
<html>
<body>
<script type="text/javascript">
window.onload = function () {
//your code here
}
</script>
</body>
</html>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744728242a4590308.html
评论列表(0条)