I'm in the process of developing a new site and have decided to use Modernizr for the first time. I'm fairly sure of the general gist of how it works however, I was looking for some advice regarding the best practise when it comes to loading jQuery and then running jQuery code.
I currently have the following that is loaded as the last item on my page:
Modernizr.load([
{
load: '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
complete: function(){
if( !window.jQuery){
Modernizr.load('/scripts/jquery-1.11.1.min.js');
}
}
},
{
load: '//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js',
complete: function () {
if ((typeof $().emulateTransitionEnd == 'function') == false) {
Modernizr.load('/scripts/bootstrap.min.js');
}
}
}
]);
This attempts to retrieve jQuery from a CDN and if it is unable to do so, loads a local version. It then repeats the process with the Javascript required for my bootstrap components on my site.
The problem I have is that I then have some jQuery code directly following this:
$(document).ready(function () {
$('.wishlist-toggle').click(function () {
var nodeId = $(this).data("node");
var id = $(this).data("id");
var type = $(this).data("type");
var addTo = $(this).data("add");
var list = $(this).data("list");
var removeFrom = $(this).data("remove");
var storedCookie = getCookie("wishlist");
var jsonString = null;
var found = false;
...
For some reason despite being after the whole jQuery loading declaration I am getting an error in my console specifying that $ is undefined. This would usually suggest that at the point at which by custom script is called, jQuery is not loaded.
My question is, how would this usually be done and what is considered the best practise in this case to ensure that jQuery truly is loaded before attempting to run the custom code.
Any help, tips or pointers would be greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…