Why can't my javascript code in the head selection get an element?

前端 未结 3 623
醉梦人生
醉梦人生 2021-01-21 16:20

I have been working on a pi calculator in javascript for a long time now and I have finally finished. The problem is that my script in the head section:

document         


        
3条回答
  •  孤独总比滥情好
    2021-01-21 16:50

    Javascript gets executed ass soon as possible, so when it's in the head tag, the document hasn't fully loaded. you can have your code run when the document is ready by using the load even

    window.addEventListener("load", function(){
        /*your code here*/
    });
    

    I guess window is supposed to be the proper way to do it, even though one would think document.load would be there ("When the document loads, do this" instead of "when the window loads do this") or run your code at the end of the body. You can still have all your methods in the head.

提交回复
热议问题