The only solution to this is to adopt a 'lazy' approach to loading, otherwise known as 'on-demand JavaScript', where code
is retrieved from the server as the need arises. This can circumvent the redundancy problem, as only a fraction of an
application need be downloaded initially, with additional functionality being acquired as necessary. This avoids the redundant
consumption of bandwidth, expedites delivery, and reduces the stress on both server and client; and there are two principal
routes to implementing the technique.
The first entails connecting to the server explicitly using an XMLHTTPRequest object, where the code that is returned is
evaluated into the execution environment. The second approach to loading on demand, the 'script-tag hack', turns upon the fact
that script elements form part of the DOM-object hierarchy for a given page. This means that an application can create a script
element, and then set the value of its src attribute to the name of a JavaScript library,
before inserting the element into the
DOM hierarchy for the page. This causes the interpreter to download the library, thus introducing its functionality into the
execution environment. Usefully, this principle also applies to CSS — setting the href of a
<link> element dynamically causes
the client to download and evaluate the corresponding style-sheet.
Note that these techniques yield the same net result, but that choosing one over the other presents certain tradeoffs. On the
one hand, the script-tag technique is asynchronous, whereas XHR allows synchronous as well as asynchronous requests. In contrast,
the script-tag technique allows retrieval of code from anywhere, whereas XHR allows requests only to the originating domain.