I recently noticed some developers creating a DocumentReady.js file and keeping all their document.ready stuff inside of it. I like this practice. I think it’s clean, but I can see how it could get out of hand. Especially if you start adding ALL of your document.ready stuff in there even though it doesn’t pertain to the majority of your pages.
I imagine you’d like to see some examples of things I have in my DocumentReady.js file. Well, I like rounded corners and I found a pretty sweet corners plugin for jQuery, which was the first thing I put in my DocumentReady.js file and it started out looking like this:
So this code says for everything with a rounded class, add the corners. Simple and I have full control and access to it on all of my pages. For more information about jquery.corners, see jquery plugins and jquery.corners demo.
Then I found myself setting the focus on all my forms on each individual page and I thought…this isn’t going to work! I hate all this redundant code and I don’t like it all over the place. I think I’ll add it to my DocumentReady.js file. So I did and it looked something like this:
var inp = $('.input-validation-error:first').get(0);
if (!inp) var inp = $('input:first').get(0);
if (inp) inp.focus();
I also started using a Bootstrapper.js and only reference it on my main template. In the bootstrapper, I have this code:
+ jsFile + '"></script>');
So there you have it. Is it a best practice? I’m not sure yet because I just started doing it in the last couple projects, but so far I really like it. What do you think?
As always, please comment if you see anywhere that I could improve or you just have a comment. Thanks for reading!