Omegalen
Omegalen

Reputation: 1496

JQuery best practices

Ok guys, three questions here. They are all pretty noobish, but I just want to get your guys' thoughts on them.

1) When writing a jquery script, should I include type?

IE:

<script type="text/javascript" charset="utf-8">
  //Jquery here
</script>

or is just an opening and closing script tag acceptable?

2) I know it's a best practice to include all JQuery just before the closing body tag, but does this also mean I include the actual jquery.js file just before body as well?

3) What if my page is reliant on jquery to look how it should (not just action events/ajax/etc). For example, I'm using a jquery plugin called datatables, which sorts through my specified database and automatically paginates/sorts/etc. I find that because I include all the scripts after the DOM loads, I see a raw format of the datatable until my datatables.js file and corresponding constructor loads. Would it be acceptable to include this before my body loads, so that this doesn't happen?

Upvotes: 3

Views: 492

Answers (1)

gdoron
gdoron

Reputation: 150253

  1. Including the type(type="text/javascript") is the best practice, though in HTML5 it's not needed as it's the default. In HTML 4 it's mandatory, but all modern browsers will read the script content as javascript if not specify, but it's still invalid according to the spec. You can read more here: Which is better: <script type="text/javascript">...</script> or <script>...</script>
  2. Putting the jQuery script in the head is a good option, but it's not mandatory, it just have to be above all other scripts using the jQuery library.
  3. Regarding to the plugin, it's hard to tell without seeing your code, and knowing how the plugin works. You can try move all the scripts to the <head> and see if it helps you. (It might still have the same effect if the plugin waits for the DOM ready. )

Upvotes: 8

Related Questions