I have some code that looks something like this, except rather than 2 sections, there are about 20, and they have real code in them:
/*------------
* Contents:
* 1. Load slider
* 2. Check form
/*------------
/*------------
* 1. Load slider
/*------------
var slider_id = 101;
var num_slides = 10;
$(document).ready(function(){
// Initiate document ready slider
});
/*------------
* 2. Check form
/*------------
var fields = {"text","number","textarea"};
$(document).ready(function(){
// Do some document ready form stuff
});
I’m trying to keep everything neat as there is going to be a handover at some stage.
My question is should I do it like I have done, or something like so:
/*------------
* 1. Load slider
* 2. Check form
/*------------
/*------------
* 1. Load slider
/*------------
var slider_id = 101;
var num_slides = 10;
/*------------
* 2. Check form
/*------------
var fields = {"text","number","textarea"};
$(document).ready(function(){
/*------------
* 1. Load slider
/*------------
// Initiate document ready slider
/*------------
* 2. Check form
/*------------
// Do some document ready form stuff
});
So, do I minimise document ready calls, or group associated content together? Just self taught so no idea about these kinds of best practises. Thanks
I’d say the general principle for this kind of thing is to avoid repeating yourself as much as possible.
Since your second example would avoid re-writing the line “$(document).ready(function() {” several times, I’d say that would be the way to go. If the initialization logic is very specific, you could write a number of “init####” methods, and have your sole initialize method call those. Two other notes:
Right now, your var
‘s are going to be global-scope, at least, unless there’s code above and below you haven’t included. That means if someone else is writing important code for the same page, perhaps for something completely seperate, that also makes a reference to “slider_id”, it may use yours. If your entire code is encapsulated inside an anonymous function (that is called either immediately, or on document ready) you can avoid that.
Finally, in general principle, you can replace “$(document).ready(function() {” with “$(function() {” and it should accomplish the same thing.