1

I' m new to javascript and I was wondering why in this script the document.write works well while innerHTML doesn't(I've given a div id timer in the body). Is it that innerHTML needs Onload event in the body part of html? If so why? (I'm calling the function writehere() in the head section of html document.

<script language="javascript">

 function writehere()

 {
       document.write("hello");

       var Timer = document.getElementById("timer");

        Timer.innerHTML = "hello";


}

writehere();

</script>

html code goes here.....

Bart
  • 19,692
  • 7
  • 68
  • 77
jathin
  • 318
  • 1
  • 12

3 Answers3

1

Most likely your issue is that the DOM isn't ready yet by the time your code executes. For your example you can probably just move it down to the bottom of your page and it will work.

In general you would want to make sure that the DOM is fully loaded before executing your javascript that needs to interact with the DOM, if you are using jQuery you can call your code in the document ready function to ensure the DOM is loaded, for example

   $(document).ready({

    });

Have a look at this SO question for vanilla javascript equivalents

What is the non-jQuery equivalent of '$(document).ready()'?

Community
  • 1
  • 1
Jack
  • 10,943
  • 13
  • 50
  • 65
  • yea after moving it to the bottom of the page ,it worked..thanks – jathin May 15 '12 at 13:50
  • "In general you would want to make sure that the DOM is fully loaded before executing your javascript" to me it sounds like a bad advice, in most cases this is not needed, and always using it sounds like (no offense to you) "I don't know what I'm doing but doing so it will work" – pomeh May 15 '12 at 14:08
  • Your right, what I should have written is "before executing Javacsript that will modify or interact with the DOM". Obvoiusly you shouldn't just stick all your code there. I have modified my answer accordingly. – Jack May 15 '12 at 14:14
  • When executing a piece a JavaScript code, you only need to ensure that "all DOM elements needed" used by the script are loaded, and not the "full DOM". So it's still a bad advice to me, check my answer to learn more about that. What do you think ? – pomeh May 15 '12 at 16:05
  • I agree with you that only your code that needs the DOM should wait until it's ready, which is why I modified my answer based on your previous comment to say "javascript that needs the DOM", are you saying you should instead check to see if the specific part of the DOM is ready as opposed to the full DOM? Regardless I appreciate that you are explaining your reasoning. – Jack May 15 '12 at 16:40
0

I think your problem is that the DOM has not been loaded yet, so there is no div element with id="Timer". You should call this method on the onLoad event.

tronbabylove
  • 1,102
  • 8
  • 12
  • If you do that then `document.write` will trash the existing document. – Quentin May 15 '12 at 13:39
  • @Quentin that's a good point - I thought the OP only included the document.write() just to show that it worked and adding the innerHTML to the div did not. – tronbabylove May 15 '12 at 13:44
  • thank you all for taking the time,so it is all about loading of DOM now i understand. – jathin May 15 '12 at 13:44
  • @Quentin: can you please tell me this, even if the dom is ready and you do a document.write isn't the document cleared ? – Dhiraj May 15 '12 at 13:48
  • @DhirajBodicherla — What do you mean "even if"? If the DOM is complete then the document will have closed, and writing to it will reopen it and trash it. The code in the question is not waiting for the DOM to complete though. – Quentin May 15 '12 at 13:50
0

It's all about HTML tags elements and execution time. In your example, the script is positioned in the head tag, so when the script is executed, the element div#timer does not exists at all.

Then you have 2 solutions:

If your DOM is not complex, and does not contains img tags or any kind of elements that need to be fetched from the network, the use of onload is not needed. You can use it in two cases:

  • you have to wait for all elements to be loaded, like images, videos etc,
  • you want to delay the execution of a low-priority script, like a script to load ads on your site for example. This script is not vital for your website and your visitor, the execution can be delayed

In general, is it considered as a good practice to put script tags at the end of the document (and so you don't need to use onload), it prevents the Flash Of Unstyled Content (FOUC). Javascript blocks your browser rendering engine. So if JavaScript tags are place before the content becomes available to the user (read: in the head tag), the browser will executed it, the DOM being almost empty, and the user will only see a blank page during this execution time.

Also, about jQuery.fn.ready method, you have to be aware of this:

$(document).ready(function() {
    // my first useless function
    console.log( "first", 1 );
});

$(document).ready(function() {
    // my second useless function
    // this function will throw an (intentional) error
    console.log( "second", someUndefinedVariable );
});

$(document).ready(function() {
    // my third useless function
    // because the previous function contains an error
    // this function will never be called
    console.log( "third ", 3 );
});

So let's say you're using some plugins, and you've some hand-written code and so on. If every plugin and your code is using the jQuery.fn.ready method, and if for some reason (let's say in some specific browser version under some circumstances) a function throw an error, then all handler after this function would be never runt...

Also, doing so, you're delaying all the "real" JavaScript execution at the end, and if you've a lot of methods to run in the queue, then you could blocks the browser during some seconds, and the user will notify it.

pomeh
  • 4,742
  • 4
  • 23
  • 44