bib
bib

Reputation: 1040

Why is the CSS not rendered when using onload event in the body tag?

I have <body onload="myFunction()"> in my html page. In the head's tag I have integrated a css file using the tag link.

However, myFunction is executed correctly but the css looks like not working correctly. I dont why? Can someone explain me the reason please?

function myFunction(){

    document.write(" <h1> Have good day</h1>")
}
body {
    font-family: Arial, Helvetica, sans-serif;
    background-color: gray;
    margin: 0 auto;
    width: 500px;
    border: 3px dotted red;
    padding: 0 2em 1em;
}
<!DOCTYPE html>

<html>
<head>


  <meta charset="utf-8" />
  <title>page0</title>

    <script type="text/javascript" src="script.js"></script>
  
  <link rel="stylesheet" type="text/css" href="styles.css" />
 

</head>

<body onload="myFunction()">

 
</body>

</html>

Upvotes: 0

Views: 183

Answers (1)

tacoshy
tacoshy

Reputation: 13012

First of all the comment is correct that document.write replaces the content of your entire document. As such your entire DOM is lost and the browser renders your content in quirks mode.

To fix your code you should use another writing method to write in your body. Use a Selector that selects the body tag: document.body > document.querySelector('body') > getElementsByTagName('body')[0]

Then use an eventListener as a trigger or a defer-attribute instead of the onload-attribute. Both will execute the script only after the DOM-Content is loaded.

defer: <script defer></script> eventListener: window.addEventListener('DOMContentLoaded', function() { ... })

AFter that, you can use a method to include the content with either appendChild method or the insertAdjacentHTML method. You should not use the innerHTML method as the other answer shows as it is much slower and will keep you open to XSS-Injection Attacks.

window.addEventListener('DOMContentLoaded', function() {
  document.body.insertAdjacentHTML('beforeend', '<h1> Have good day</h1>');
});
body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: gray;
  margin: 0 auto;
  width: 500px;
  border: 3px dotted red;
  padding: 0 2em 1em;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>page0</title>
    <script type="text/javascript" src="script.js" defer></script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
  <body>
  
  </body>
</html>

PS: Remember that you can remove either the defer-attribute or the eventListener from the example. Only one is needed.

Upvotes: 2

Related Questions