AMD: what is the purpose in javascript context?

*爱你&永不变心* 提交于 2021-01-27 13:15:31

问题


Regarding AMD (Asynchronous Module Definition ) I read the phase like this:

The AMD format comes from wanting a module format that was better than today's "write a bunch of script tags with implicit dependencies that you have to manually order" and something that was easy to use directly in the browser.

What is the the purpose in javascript context? Can you make some example? pro et contro of using AMD?


回答1:


Long before JavaScript gained a native module system, the only way to put scripts onto a page were <script> elements. These executed in sequence, in the order they appear on the HTML. This means that if your script relied on jQuery, then jQuery's <script> has to come before your script's <script>. Otherwise, it blows up.

It's not uncommon to logically split an app into multiple files, especially as the app grows. But using this system of manually ordering scripts becomes a nightmare quickly. Your scripts have implicit dependencies whose management is defined elsewhere. This is where AMD comes in.

AMD is a module specification and RequireJS is an implementation of such system. Simply put, it's a wrapper around your code that 1) keeps your script inert until invoked, 2) allows your script to explicitly define its dependencies and, 3) allows the module system to work out which dependencies execute in what order.

Here's a rough example:

// your-app.js
define(['jquery', 'underscore'], function($, _){
  // Your script sits in this "wrapper" function.
  // RequireJS now knows app.js needs jquery and underscore.
  // It loads and executes them first before your script.
})

// jquery.js
define('jquery', [], function(){
  // jQuery stuff
  return jQuery
})

// underscore.js
define('underscore', [], function(){
  // underscore stuff
  return underscore
})

// Then on your HTML, load up your app.
<script data-main="path/to/app.js" src="path/to/require.js"></script>



回答2:


It's common for Javascript libraries that depend on each other to require that they are loaded in a specific order. For example, the script tag that includes the jQuery library has to come before the script tag that includes the jQuery UI library.

If the libraries were using AMD, they could be included in any order. The AMD library would take care of initialising the libraries in the correct order, because you specify which library depenends on which.

(Somewhat ironically, the script tag that includes the AMD library of course has to come before the code that include any libraries using AMD...)



来源:https://stackoverflow.com/questions/10160343/amd-what-is-the-purpose-in-javascript-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!