Search code examples
xmlhttprequestrequirejsamd

How is XHR a viable alternative to asynchronous module definition?


I'm learning about the case for asynchronous module definition (AMD) from here but am not quite clear about the below:

It is tempting to use XMLHttpRequest (XHR) to load the scripts. If XHR is used, then we can massage the text above -- we can do a regexp to find require() calls, make sure we load those scripts, then use eval() or script elements that have their body text set to the text of the script loaded via XHR.

XHR is using ajax or something to make a call to grab a resource from the database, correct? What does the eval() or script elements have to do with this? An example would be very helpful


Solution

  • That part of RequireJS' documentation is explaining why using XHR rather than doing what RequireJS does is problematic.

    XHR is using ajax or something to make a call to grab a resource from the database, correct?

    XHR is what allows you to make an Ajax call. jQuery's $.ajax for instance creates an XHR instance for you and uses it to perform the query. How the server responds depends on how the server is designed. Most of the servers I've developed won't use a database to answer a request made to a URL that corresponds to a JavaScript file. The file is just read from the file system and sent back to the client.

    What does the eval() or script elements have to do with this?

    Once the request is over, what you have is a string that contains JavaScript. You've fetched the code of your module but presumably you also want to execute it. eval is one way to do it but it has the disadvantages mentioned in the documentation. Another way to do it would be to create a script element whose body is the code you've fetched, and then insert this script in the DOM but this also has issues, as explained in the documentation you refer to.