0

Is it "okay" to have an HTML document embedded inside the body tag of another HTML document?

The reason why I want to do this is so that I can call a javascript body onload -- I cannot do that in the main HTML document because the main HTML code is dynamically generated by a controller (Yii) that controls other pages and I do not want to edit it.

*By the way, I tried it and it seems to work fine now, but I just want to be sure that the page will not break in the future for whatever reason.

<html>
<head>
<body>    
    <html>
    <head>
        <script type="text/javascript>
        function somefunction(){
        }
        </script>
    </head>
    <body onload="javascript:somefunction()">    
    </body>
    </html>
</body>
</html>
m0rtimer
  • 2,023
  • 1
  • 25
  • 31
  • Check http://stackoverflow.com/questions/2035462/multiple-htmlbody-html-body-in-same-file – K'' Aug 19 '11 at 13:25

2 Answers2

3

If all you want to do is attach an onload event, you're going about it the wrong way.

All you have to do is add a script element that attaches an onload event:

<script type="text/javascript">

  function somefunction()
  {
    ...do stuff...
  }


  document.body.onload = somefunction;

</script>

Alternatively, if you've appended your JS files at the bottom of the page, they will be able to interact with the DOM similarly to how onload works. The reason to use onload is only so that the elements defined within the web page have been added to the DOM by the time a function is executed. If your scripts are after your content, the elements will be in the DOM.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Also note that `onload` will wait for the page's assets, like images, to load before firing. Putting the script at the bottom of `` not only guarantees DOM access like `onload` does, but also fires first. – Matchu Aug 19 '11 at 13:26
  • Scripts placed a the bottom of the page do not execute identically to `onload` the primary difference being the first script at the bottom wont have access to: subsequent scripts, the code they contain, any functionality they add. `onload` means *everything* has loaded, which allows for cross-script references with impunity. `document.onreadystatechange` is another function to look into as well. – zzzzBov Aug 19 '11 at 13:29
1

No, that's bad HTML.

Just put your JavaScript at the bottom before </body>.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445