When you’re dealing with the DOM it’s important to execute your code only after the page is fully loaded. If you don’t, there’s a good chance the DOM won’t be
created by the time your code executes.
Now Let’s think about what just happened when your code run. you put your js code in the header tag of the page, so it begins executing before the browser even sees the rest of the page. That’s a big problem because that span element with an id of “news” doesn’t exist, yet.
So what happened exactly? The call to getElementById returns null instead of the element you want, causing an error, and the browser, being the good sport that it is, just keeps moving and renders the page anyway, but without the change to the DOM at the first time.
How do you fix this? Well, you could move your code to the bottom of the body, but there’s actually a more foolproof way to make sure this code runs at the right time; a way to tell the browser “run my code after you’ve fully loaded in the page and created the DOM.” Besides moving the code to the bottom of the body, there’s another—and, one might argue—cleaner way to do it with code.
Here’s how it works: first create a function that has the code you’d like
executed once the page is fully loaded. After you’ve done that, you take the
window object, and assign the function to its onload property. The window object will call any function you’ve assigned to its onload property, but only after the page is fully loaded. Check This out:-
<html>
<head>
<script>
var i=0;
var u=0; //0:redy for the next FX
var newstext;
function renews() {
if(i%2==0){
newstext = "aaa";
} else {
newstext = "bbb";
}
document.getElementById("news").innerHTML = newstext;
i++;
}
//renews(); // this doesn't work
window.onload = renews; //But this will work
setInterval(function(){
renews();
},3000);
</script>
</head>
<body>
<span id ="news">test</span>
</body>
Now even if you put your JavaScript code in a separated JS file and import it in the header tag instead of moving it to the end of the body your code will work just fine.