When to use “[removed]”?

前端 未结 6 1915
终归单人心
终归单人心 2020-12-05 00:03

In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?

For example, if I want to

6条回答
  •  春和景丽
    2020-12-05 00:35

    The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.

    document.ready is a great alternative to window.onload if you're using jQuery.

    See here: window.onload vs $(document).ready()

提交回复
热议问题