Best Practices for onload Javascript -


What is the best way to handle multiple different load scripts spread across multiple pages?

For example, I have 50 different pages, and on every page, I want to set a separate button click handler when the Dome is ready.

Is it best to set this on each individual page in such a way,

 & lt; An id = "link 1" href = "#" onclick = "myFunc ()" /> 

or a very long document ready function in any external JS file,

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

or split each ($ ('link')) {} puts the section in script tags and places them on the appropriate pages,

or at the end, split every ($ ('link')) {} Is different JS file and load per page relevant to the section?

Solution 1 Looks like elegant and is relatively flawed, solution 2 will take a very long load function, solution 3 is less irrelevant, then 1 is not good yet, and the solution will load 4, the user can download a different JS file per page

Is any of these the best (or worst) ones or is there any solution I'm thinking about? 5

Edit: I About Design Patterns It's not that which load work is appropriate to use.

< P> Have you thought of creating a class for every kind of behavior that you want to add to an element? This way, you can reuse functionality between the pages, just overlap.

For example, suppose on some pages you want a button that pops up some additional information on the page. Your HTML may look like this:

  & lt; A href = "#" class = "more-info" & gt; More info & lt; / A & gt;  

And your javascript can look like this:

  jQuery ("more info"). Click (function () {...});  

If you are stuck in some kind of conference, you can add more than one category to the link and you can do some different things (if you need to The element will give stack to the event handlers).

In fact, you are focusing on behavior for each type of elements, which are attached to Javascript, rather than to add functionality to specific ID elements.

D also suggests putting all JavaScript in a limited number of common files or limited files. The main reason is that, after the first page load, JavaScript will be cached and will not need to be loaded on every page. Another reason is that it will encourage you to develop general behavior for the buttons on the site.

In any case, I discourage the attachment of Alic directly into HTML (Option # 1). It's intrusive and limits flexibility with your javascript.

Edit: I did not know that Diodius had posted a very similar reply (which I agree).


Comments