What's the difference between using Require.JS amd simply creating a <script>
element in the DOM?
My understanding of Require.JS is that it offers the ability to load dependencies, but can this not simply be done by creating a <script>
element that loads the necessary external JS file?
For example, lets assume I have the function doStuff()
, which requires the function needMe()
. doStuff()
is in the external file do_stuff.js
, while needMe()
is in the external file need_me.js
.
Doing this the Require.JS way:
define(['need_me'],function(){
function doStuff(){
//do some stuff
needMe();
//do some more stuff
}
});
Doing this by simply creating a script element:
function doStuff(){
var scriptElement = document.createElement('script');
scriptElement.src = 'need_me.js';
scriptElement.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(scriptElement);
//do some stuff
needMe();
//do some more stuff
}
Both of these work. However, the second version doesn't require me to load all of the Require.js library. I don't really see any functional difference...
Here is the nice article on ajaxian.com as to why use it:
RequireJS: Asynchronous JavaScript loading