Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>What advantages does Require.JS offer in comparison to simply creating a element in the DOM? </p> </blockquote> <p>In your example, you're creating the script tag asynchronously, which means your <code>needMe()</code> function would be invoked <em>before</em> the need_me.js file finishes loading. This results in uncaught exceptions where your function is not defined.</p> <p>Instead, to make what you're suggesting actually work, you'd need to do something like this:</p> <pre><code>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); } </code></pre> <p>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.</p> <p>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 <em>using</em> 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.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload