Run JavaScript function when the DOM is “ready”?

前端 未结 7 2116
一生所求
一生所求 2020-12-03 10:04

I\'m using a JavaScript upload script that says to run the initialize function as soon as the DOM is ready. I currently have it working just fine with either a call to the f

相关标签:
7条回答
  • 2020-12-03 10:28

    The easiest solution is using jQuery and its $(document).ready(function() { .... }); function. Instead of .... you put your own code.

    Note that it basically does the same thing @Shadow2531 suggested, but also works in old browsers not supporting that event.

    0 讨论(0)
  • 2020-12-03 10:31

    The DOM is usually ready before onLoad runs. onLoad only runs after everything loads - external scripts, images, stylesheets, etc.

    But the DOM, i.e. the HTML structure is ready before that. If you run the code at the bottom of the page (or after the parts of the page the script works with) that will work fine as well.

    0 讨论(0)
  • 2020-12-03 10:36

    Get jQuery and use the following code.

    $(document).ready(function(){
        // Do stuff
    });
    
    0 讨论(0)
  • 2020-12-03 10:37
    <script>
        window.addEventListener("DOMContentLoaded", function() {
            // do stuff
        }, false);
    </script>
    

    You do that so you know all the parsed elements are available in the DOM etc.

    0 讨论(0)
  • 2020-12-03 10:39

    As you probably know you should not run init functions before the DOM is fully loaded.

    The reason you must run the init function as soon as the DOM is ready, is that once the page has loaded the user starts hitting buttons etc. You have to minimize the small inavoidable gap where the page is loaded and the init-functions haven't run yet. If this gap gets too big (ie. too long time) your user might experience inappropiate behaviour... (ie. your upload will not work).

    Other users have provided fine examples of how to call the init function, so I will not repeat it here... ;)

    0 讨论(0)
  • 2020-12-03 10:40

    In 2015 you have two options with modern browsers:

    document.onload

    • this fires when the document is loaded, but other resources (most notably images) have not necessarily finished loading.

    window.onload

    • this fires when the document is loaded, AND all other resources (again, most notably images) are loaded.

    Both of the above events would be better utilized with window.addEventListener() of course, as multiple listeners would be allowed.

    0 讨论(0)
提交回复
热议问题