January 15, 2014
Ready and Load
One of the reason's I've chosen to reprogram my header's menu functionality is there was one important thing about jQuery I forgot about when I initially created my CMS: Where to put the jQuery code.
Often times, knowing how to use jQuery's .ready
and .load
functions is never explained in such a way that most people who just want to pick up jQuery and go with it find themselves with either code they thing does not work or code that feels like it's in the wrong part of a document.
Firstly, the proper syntax of using JavaScript is generally to put your code in the <head>
element in a <script>
element. It's a convention that is often not obeyed by programmers, especially since it is permissible to put JavaScript in the body
either by using element attributes or by just putting a <script>
element in the body.
In HTML5, the <script>
element has a new attribute called defer
. The purpose of defer
is to put off executing a block of JavaScript in a page until it has finished parsing. However, many browsers still don't support it. And after trying it out, I find this to be a bad idea to use especially since a page can be loaded but not done parsing. Also, defer
is meant for external scripts. So writing you <script>
block where ever it is in the page will still make the code run even if you use a defer
attribute.
Thankfully, jQuery has a better, and more elegant, way of doing this.
The above code will change the display of any <pre>
element that follows a <h3>
. (Though, if you wish to use this example, add h3 + pre { display:none; }
inside a <style>
element preceding the <script>
element.)
Without using $(document).ready(handler)
, the code inside does not work where it is. To make it work without it, $("h3").click(...)
would need to be placed inside a <script>
block, located at the end of the HTML document where </body>
is.
The other important issue is how to use .load
, not the depreciated .load
function but the proper .load
function.
Some of jQuery's functions, especially the ones that use AJAX will not work by playing around with some place like file:///home/you/Sandbox/file.html
. When you want to do something that has AJAX involved in it, your sandbox URL should be http://localhost/Sandbox/file.html
. Blame the "Same-origin policy" used in just about every browser. If you are lucky to have something like Apache HTTP Server or Nginx installed as you Hypertext Transfer Protocol Daemon (httpd) or "web server", all that is needed is to move the file you are playing with to where your web server calls home. For Linux users, that means somewhere in /var/www/
. (See my last post for how to create a Sandbox folder).
Note that the .load
function is inside .ready
. This is ideal because you want to be "ready" before you "load" anything new anyway. But these are simple examples. I'm sure you can come up with something more complex. With this important knowledge, you can do so with confidence and write code more professionally.