created on 07 May 2008, by Syndication, read more…
David Kees has written about Using Prototype to Load Javascript Files, which is an implementation of the general technique of loading functionality via scripts based on the availability of DOM elements.
He started using the technique to scratch an itch:
The calendar on this site only appears on pages that show blog-related information. That calendar is enhanced with Javascript allowing you to change the month displayed by the calendar without reloading the rest of the page. So, in order to ensure that these enhancements would be available everywhere the calendar is, I figured I had two options:
Code the inclusion of the Javascript file into every page which requires it. While a good solution, and one that has worked well in the past, sometimes it can be difficult to remember or realize that you've forgotten to include the file when you add new pages that require it.
Find a way to automatically include the file when it's needed. This would avoid the need to remember the need to include it when adding new pages that require it, but would result in a little more Javascript going on when the page loads.