We've all seen a Sitecore Layout that looks like this:
If that sounds familiar, I'd suggest a different approach.
Change Our Layout
Write The Code
Here is an implementation of the AddJS() method we use.
Class containing overloaded AddJS() method
Calling AddJS() from a Sublayout
This technique really becomes powerful when combined with AMD Loaders (e.g. RequireJS) in Sitecore. They allow you to load a single JS file and have all its dependencies loaded on demand, asyncronously. We hope to write about using RequreJS in the near future.
This technique will not work with Sublayout caching enabled. Because Sitecore caches the rendered HTML, the C# Page_Load() method is only executed on the first visit.
That said, it can also be act as a reminder to keep your Sublayouts lean and push expensive data requests asyncronohously to the client-side. Thanks for reading!