Search code examples
javascriptasynchronousamd

How can you capture the result of a HTML script tag in a variable?


I have been reading about AMD and implementations like requirejs. Most of the resources covers the usage and API's.

But, when it comes to implementing this, how can you load a JavaScript file into a variable just like that? For example, you can see functions like this:

define(['jquery'], function($){
});

var jquery = require('./jquery');

From an API consumer's perspective, all I can understand is that the file jquery.jshas magically become $, jQuery etc? How is that achieved?

Any examples would be helpful.

How do AMD loaders work under the hood? is a helpful read.

Edit: I think the eval answers below are nice because it actually is an eval problem in some ways. But I would like to know this from the perspective of an AMD specs implementation.


Solution

  • The way define works under the hood is not by loading an "HTML Script into a variable". Typically a normal script can have multiple variables so it doesn't make sense to capture the value a variable! The eval approaches can probably do something like that if needed. It captures all that is there in the JavaScript source code.

    The real key in AMD is that the define API maps a name to a function. Whenever you require with that name, it would just call that function and return the value to you. This return value is expected to be the module. This is a convention that makes everything work!

    In other words, AMD uses an interesting convention (design pattern) to ensure that we get a modularization effect in JavaScript code. It is one level of indirection. Instead of the normal style of "write your code and get it executed in the global scope" paradigm, you just write a function that returns a single value that captures all the things you want to expose as a module to the consumer!