Reputation: 797
I place jquery.js
on my footer before </body>
<script type="text/javascript" src="/js/jquery.js"></script>
And why this code is not firing? But when I move jquery.js on header before </head>
it working fine..
$(document).ready(function () {
$("#sub-category").hide();
$("#main-category").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "/select-category/",
data: dataString,
cache: false,
success: function (html) {
$("#sub-category").show();
$("#sub-category").html(html);
}
});
});
});
Let me know why code above is not firing when I include jquery.js
on my footer.
Upvotes: 1
Views: 5876
Reputation: 121
Place the following in your page header:
<script type="text/javascript">
// Place-holder function to handle jquery, before jquery is loaded (as jquery is loaded in the footer)
(function(w,d,u){w.readyQ=[];w.bindReadyQ=[];function p(x,y){if(x=="ready"){w.bindReadyQ.push(y);}else{w.readyQ.push(x);}};var a={ready:p,bind:p};w.$=w.jQuery=function(f){if(f===d||f===u){return a}else{p(f)}}})(window,document)
</script>
Place this in the footer after you load the jquery script:
<script type="text/javascript">
// This will make it possible to declare jquery inline
(function($,d){$.each(readyQ,function(i,f){$(f)});$.each(bindReadyQ,function(i,f){$(d).bind("ready",f)})})(jQuery,document)
</script>
Then declare all of your jquery inline in a $(document).ready(function(){}); call and it works.
I can't remember where I found this code, but it works great.
Upvotes: 1
Reputation: 10529
I bet you actually put the $(document).ready(function () { });
block before jQuery library. jQuery has to be loaded even before $(document).ready(function () { });
block in order to make it work. However, in all cases, keep jQuery in <head>
, that's the right place for it
Upvotes: 2
Reputation: 7196
I have created a simple shim for this reason precisely. It creates a global jQuery (and $) object that are only capable of queuing functions for domReady. It is very tiny so you can inline it in the HEAD tag (inline to avoid the whole issue of a dns lookup, latency, etc) and then any code in the body written as you describe will still function properly.
https://github.com/withjam/jqshim-head
The shim essentially stores all of the functions passed to jQuery() or jQuery().ready(), waits for the real jQuery to be available, then passes them into the real jQuery() call to proceed with the isDomReady cycle.
Let me know if that helps.
Upvotes: 1
Reputation: 442
Is your script included before 'jquery.js'? Then it won't work because of not being able to access the jQuery functions.
For helping to debug consider using the add-on 'Firebug' in Firefox or the integrated Developer Tools in Chrome/Chromium. Both open by pressing F12.
Upvotes: 0