I have a very large project that has several external javascript files that I would like to unify in a single large one to optimize server load.
The problem is that many of these scripts have they own (document).ready() events that targets element that are only available on that page.
Unifying everything would put a lot of (different) (document).ready() in a single file and most of them will target elements that are not on the page, is this a problem?
What is the correct way to approach this?
EDIT: Clarification: I mean unify hundreds of javascript file included in they own tag in a single file, so I can minify it.
It sounds to me like you have a different javascript file included on each page and you want to consolidate them together.
If that is what you are trying to do then the simplest way is to just concatenate all the javascript into a single file. It is fine to have multiple ready calls in the same file. Also jQuery should not error if elements are not present on the page so long as you use jQuery methods to do things (for example
$('.element').show()would be fine, but$('.element')[0].style.display = 'block';would error if the element is not present on that page.Putting them all together could have unexpected consequences though if you have things that you only want to apply to specific pages. One way to handle this would be to check which page you are on before attaching specific events. You can do this by checking for specific elements on the page like
or
Or you could use an id or other means to differentiate.
You could now make one
$(document).ready(init);call at the bottom of your javascript and the init function could decide what needs to be initialized for that page.Hope this helps!