As mentioned in the comment, your initialization order is messed up. You can use window.onload
to fix it:
<script type="text/javascript">
window.onload = function() {
document.getElementById('ball').style.backgroundColor="red";
};
</script>
Note also that you can only have one onload
trigger function. Here are some ideas on how to support multiple trigger functions. The easiest, is of course, to just use JQuery's ready function.
Another way is to put the <script> tag into the body after the DOM element(s) that it depends on. This is often encouraged for performance reasons, but it tends to make things less readable.
The reason as to why <script> tags in the head are executed in sequence (instead of delaying execution until after the DOM has loaded) is: Performance. For example, you sometimes might want to start asynchronous requests before the document has finished loading. If you are not concerned about performance, it's safer to execute them "onload".
Ultimately, there are a lot of considerations to be made when placing your <script> tag. If you want to learn more, this might be a good starting point.
About the second part of your question: The reason as to why it works in JSFiddle is that, by default, it executes scripts onload. You can reproduce the bug on JSfiddle by choosing "no wrap - in head": http://jsfiddle.net/aDuwg/.