Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need JavaScript module loading and what is the difference between all these loaders?

Question 1:

Why do I need to asynchrously load my JavaScript files in a web page? I can see the rationale for it on the server side, but if I know all the files I need to load in the client, why shouldn't I concatenate all my source files into 1 file and load that on page load? Is the first initial page load so important that future operations may be slowed down due to latency in retrieving every JS file?

Question 2:

Assuming the answer to question 1 is that I need to load JS files separately:

AMD loads each JS file asynchrously, CommonJS loads synchronously. CJS is required for server-side loading (that's how Node.js works, if I'm not mistaken). AMD seems to be a better fit for the client. Thus, the only reason to use CJS in the client is to share code with the server.

Is there a way to make AMD and CJS play nicely, so that client JS files can be loaded asynchronously but still have CJS syntax?

(What exactly does require.js do? I cannot for the life of me read between the lines on their website.)

like image 798
Oliver Zheng Avatar asked Oct 02 '12 20:10

Oliver Zheng


1 Answers

You do not "need" to load javascript files asynchronously or via some custom loader. Here are some reasons when asynchronous loading or custom loading might provide a benefit:

  • When the javascript file is not normally needed and you might want to load it upon demand rather than all the time
  • When the javascript file is not needed for initial page display and you want to maximize the speed of first display for your page
  • When you want to control the timing of exactly when the javascript file is loaded
  • When you are deciding, based upon some condition, whether to load the javascript file or not (for example, if loading from a CDN failed, you might load from a backup location)
  • When you want script loading to proceed in parallel with other things rather than serialized one after another

If you don't need any of these benefits or some other benefit provided by programmatic loading, then you can just use the normal <script> tags and let them load synchronously.

like image 131
jfriend00 Avatar answered Nov 15 '22 17:11

jfriend00