Best practices for onload Javascript

What is the best way to handle multiple onload loading scripts on different pages?

For example, I have 50 different pages, and on each page I want to set a different button click handler when dom is ready.

Is it better to install onclicks as on every single page,

<a id="link1" href="#" onclick="myFunc()" />

Or a very long documentation in an external js file,

Element.observe (window, 'load', function () {
  if ($ ('link1')) {
    // set click handler
  }
  if ($ ('link2')) {
   // set click hanlder
  }
  ...
}

Or separate each section if ($('link')) {}into script tags and place them on the appropriate pages,

, , if ($('link')) {} js ?

1 , 2 , 3 , 1, , 4 , js , .

- ( ) 5, ?

: , , onload .

+3
7

, ? , , , .

, , , , . html :

<a href="#" class="more-info">More info</a>

JavaScript :

jQuery(".more-info").click(function() { ... });

- , , ( jQuery ).

, , JavaScript, , .

JavaScript . , JavaScript . , , , .

, onlick html ( # 1). JavaScript.

: , ( ).

+3

JQuery, ,

  $(document).ready(function() {

      // jQuery goodness here.
 });
+1

, , , ?

...

-

<a id="link1" href="#" onclick="myFunc()" />

.

-

Element.observe(window, 'load', function() {
  if ($('link1')) {
    // set click handler
  }
  if ($('link2')) {
   // set click hanlder
  }
  ...
}

javascript .

- , , - .

4 - , , , if ($ ('link')) {}, ? , javascript, .

+1

:

<a class="loadevent functionA" id="link1" href="#" onclick="myFunc()" />

... ...

<a class="loadevent functionB" id="link1" href="#" onclick="myFunc()" />

" loadevent" , - , . , , , , .

+1

, :

$(document.ready(function() {
  // A
});
$(document.ready(function() {
  // B
});
$(document.ready(function() {
  // C
});

( , ), , ready() onload(). jQuery API docs:

, DOM .

load():

$(document).load(function() {
  // do stuff
});

...

0

jQuery kneejerk, , JS, , script ( onload, ), # 4, JS script , - (? XSLT).

, .

0

, ...

, , , , , , , , ...

, , - () (jquery, mootools !), - ...

, , , , .., ! o]

0

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


All Articles