I work with a proprietary CMS every day, and one of the easiest ways to customize individual sites is with the theme.js that is present on all pages. The preferred approach is usually jQuery, but vanilla javascript is also encouraged. In a sense, think of it as being like the functions file in Wordpress. It's not a perfect solution, and more it just tacked on to do new things, but it's what it is.
When I add isolated functions, things that aren't called but just act when the page loads, I want to add them in a way that's more standards compliant and less prone to bugs. One thing I want to avoid is blatant global context(s).
Example of how I was shown to do it at first:
$(function() {
$('div.target').append('<p>New stuff</p>');
});
We talked it over, and it was agreed to encapsulate:
(function() {
var foo;
if (bar) {
// some code
}
}());
Problem is, when I run the code exactly like that, it doesn't take effect. So, I changed it to this:
(function($) {
$(document).ready(function() {
$('div.target').append('<p>New stuff</p>');
});
}(jQuery));
That works, but I don't want it to defeat the purpose. Is adding $(document).ready(function()
back peddling our endeavor to encapsulate and avoid global context with small functions?
$(function() {
is just a shortcut to $(document).ready(function() {
.
In both cases you are inside a function, so as long as you use the var
when assigning variables they won't pollute the global scope.
Note that you can use multiple ready
handlers with no problem.