Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: onClick="" vs. jQuery.Click()

I have many pages with onClick-Events(every page got other elements with it's own onClick-Event). All pages get included to one main-Page (index.php)

Thus, I can't put all of the jQuery onClick-Events in the head of the page (because the <head> is just in index.php, not in the included pages)

Is it now better to either make a <script>...</script> in every page I include? Because this wouldn't be in the <head>.

Or should I use the HTML-attribute onClick="" ?

like image 779
Quantm Avatar asked Feb 21 '14 13:02

Quantm


2 Answers

Is it now better to either make a ... in every page I include? Because this wouldn't be in the .

<script> tags don't need to be in the head, actually, the best place (performance-wise) is right before the closing </body>. And yes, you also want to use external JS files as much as possible.

Or should I use the HTML-attribute onClick="" ? [...] I can't put all of the jQuery onClick-Events in the head of the page (because the is just in index.php, not in the included pages)

In general, you almost always want to avoid adding lots of events, instead, you want to take advantage of event bubbling using jQuery.on.

An example usage might be:

$(document).ready(function() {
    $('body').on('click', '.myselector', function(e) {
        alert('Parameter: ' + $(this).attr('data-param'));
    });
});

You HTML would look something like:

<a href="#" class="myselector" data-param="Hello!">This is a button</a>

This will bind only one event, on the body. When you click on anything inside the body, the event will bubble up to the body, and get executed if you clicked inside this selector. If there's no .myselector on the page, it'll do nothing, so that would be okay.

like image 121
Martin Tournoij Avatar answered Sep 22 '22 11:09

Martin Tournoij


Really, all JavaScript should be placed in external files. This is for performance and maintainability.

Performance because external scripts can be cached by the browser, decreasing loading times.

Maintainability because you don't end up having to trawl through massive HMTL documents to get to a bit of JavaScript.

JavaScript within HMTL can also mess with the parser, which you need to be aware of.

If it's not possible to include all your scripts in external files you should really re-think your website's architecture, as this is how it should be.

like image 24
Kevin Avatar answered Sep 25 '22 11:09

Kevin