Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put all that jQuery JavaScript code?

From the documentation I've found this example:

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially shown, we can hide it slowly:

$('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

I remember from 5 years ago, that you should NEVER ever refer to any element until it was defined. Does this rule still apply? So I would have to put all that code in the footer of my web page? Or can I put it in a separate file and import it in the footer? What's best practice?

like image 929
Proud Member Avatar asked Oct 15 '10 14:10

Proud Member


People also ask

Where do I put jQuery in JavaScript?

jQuery code is implemented as part of JavaScript scripts. To add jQuery and JavaScript to your web pages, first add a <script> tag that loads the jQuery library, and then add your own <script> tags with your custom code.

Where do I declare jQuery?

A simple solution for anyone learning jQuery is to always declare your jQuery code inside the document ready function. This is to ensure that all of the html page elements also known as the DOM (Document Object Model) have loaded before any jQuery code is run.

Should I put all my JavaScript in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.

Where should JavaScript be placed?

Using the script tag to include an external JavaScript file The script tag should either be included between the <head> tags or just before the closing <body> tag in your HTML document. JavaScript is often placed before the closing body tag to help reduce the page loading time.


1 Answers

The recommended way of doing this is putting all initialization code into $(document).ready, like so:

$(document).ready(function() {
   $('#foobar').click(function(event) { alert("You Clicked Me!"); });
});
like image 197
tdammers Avatar answered Oct 20 '22 00:10

tdammers