Alternative to use body load

I am a newbie and I play around trying to achieve something using javascript.

I have a function that should act as soon as my page loads, but I do not want to use. <body onload="init()"Is there another alternative?

            <script type="text/javascript">
            function init() {
            container = document.createElement('div');
            <script>

            <body onload="init()">

            </body>
+4
source share
4 answers

You can also do:

window.onload = function() {
 init();
}
+1
source

Call it from the handler load:

function init() {
  container = document.createElement('div');

  // ...
}

window.addEventListener("load", init);
+6
source

, jquery, manaully

<!-- Google CDN -->

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head> 

Google CDN

<!-- Microsoft CDN -->

<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head> 

Microsoft CDN. jquery -.

<script type="text/javascript">
 $(window).on('load",function(){
   // your code
 });
</script>

, , jquery . javasript, jquery: .

<script>
  window.onload = function() { 
    //your code
  }
</script>

;)

: , ! - ( ),

$(document).ready(function(){
 //your code
});

jquery

document.addEventListener("DOMContentLoaded", function(event) { 
  //your code
});

javascript

+1

, , - : JQuery

$(document).ready(function(){
   // code loaded..
});

JQuery

// this code is bad to practise
    <script type="text/javascript">
        function init() {
            // Put your code here
        }
        window.onload = init;
    </script>
-3

Source: https://habr.com/ru/post/1616785/


All Articles