Could someone tell me if the location of the script tag matters while using JQuery?
For example:
<script>
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
</script>
<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>
The above code does not work as needed but the following works,
<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>
<script>
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
</script>
Why did the second one work? Is it because the code is working serially, top to bottom? Also, if the first code is inside .ready(), then the position does not matter.
The location does matter. In the first case you are placing the script before the DOM element meaning that you need to wrap it in a
document.readyhandler otherwise at the moment you are attaching the.clickhandler the anchor doesn’t yet exist. Here’s how you could wrap the script into a document ready meaning that the .click handler will be attached only when the full DOM is loaded and ready to be manipulated:Placing the script at the end of the document (just before the closing
<body>tag) is also a good practice (actually it is one of the recommendations of Best Practices for Speeding Up Your Web Site) and in this case you don’t need to wrap it in adocument.ready.