What's the difference between Require.js and simply creating a <script> element in the DOM?
What advantages does Require.JS offer in comparison to simply creating a element in the DOM?
In your example, you're creating the script tag asynchronously, which means your needMe()
function would be invoked before the need_me.js file finishes loading. This results in uncaught exceptions where your function is not defined.
Instead, to make what you're suggesting actually work, you'd need to do something like this:
function doStuff(){
var scriptElement = document.createElement('script');
scriptElement.src = 'need_me.js';
scriptElement.type = 'text/javascript';
scriptElement.addEventListener("load",
function() {
console.log("script loaded - now it's safe to use it!");
// do some stuff
needMe();
//do some more stuff
}, false);
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
Arguably, it may or may not be best to use a package manager such as RequireJS or to utilize a pure-JavaScript strategy as demonstrated above. While your Web application may load faster, invoking functionality and features on the site would be slower since it would involve waiting for resources to load before that action could be performed.
If a Web application is built as a single-page app, then consider that people won't actually be reloading the page very often. In these cases, preloading everything would help make the experience seem faster when actually using the app. In these cases, you're right, one can merely load all resources simply by including the script tags in the head or body of the page.
However, if building a website or a Web application that follows the more traditional model where one transitions from page to page, causing resources to be reloaded, a lazy-loading approach may help speed up these transitions.
Here is the nice article on ajaxian.com as to why use it:
RequireJS: Asynchronous JavaScript loading
- some sort of #include/import/require
- ability to load nested dependencies
- ease of use for developer but then backed by an optimization tool that helps deployment
Some other very pointed reasons why using RequireJS makes sense:
- Managing your own dependencies rapidly falls apart for sizable projects.
- You can have as many small files as you want, and don't have to worry about keeping track of dependencies or load order.
- RequireJS makes it possible to write an entire, modular app without touching window object.
Taken from rmurphey's comments here in this Gist.
Layers of abstraction can be a nightmare to learn and adjust to, but when it serves a purpose and does it well, it just makes sense.