Document ready và window load

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The body.onload() event will be called once the DOM and all associated resources like images got loaded. Basically, onload()will be called when the page has been fully loaded with entire images, iframes and stylesheets, etc.

    For example, if our page contains a larger size image, so onload() event will wait till the image is fully loaded.
     

    Example:

    HTML

    <html lang="en">

    <head>

        <script 

        script>

        <meta charset="UTF-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" 

              content="width=device-width, initial-scale=1.0">

    head>

    <body onload="loadBody()">

        <h2>GeeksForGeeksh2>

        <script>

           function loadBody(){

               alert("page loaded");

           }

        script>

    body>

    html>

    Output:

    Document ready và window load

    body onload

    The document.ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.

    We can have multiple document.ready() function in our code but only one body.onload() is allowed.

    Example:

    HTML

    <html lang="en">

    <head>

        <meta charset="UTF-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" 

              content="width=device-width, initial-scale=1.0">

    head>

    <body onload="loadBody()">

        <h2>GeeksForGeeksh2>

        <script>

           $(document).ready(function(){

               alert("ready - page loaded")

           })

        script>

    body>

    html>

    Output:

    Document ready và window load

    DOM is ready

    Difference between body.onload and document.ready:

    body.onload()document.ready()
    onload() will be called only when everything gets loaded. This function is called as soon as DOM is loaded.
    It will wait till all resources like images, iframes, objects, scripts get loaded. It will be called once DOM is loaded.
    We can have only one body.onload() function. We can have multiple documents.ready() function in our page.