Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is exactly define(function(require){...}) in JavaScript

I understand that define is used to define a module, and function is an anonymous function, but what does the argument 'require' in the function hold?

If I write anything in define(function(require){...}), when will this be called? How to give a call to his anonymous function?

Please help, I am new to advanced JS.

like image 251
Tehreem Avatar asked Oct 07 '14 05:10

Tehreem


1 Answers

This is part of the requireJs api, it's not vanilla JS.

You can see the full docs in here: http://requirejs.org/docs/api.html#define

"require" in the above example is actually the "require" code, this pattern allows you to require a JS and, than only when loading the JS is completed, load yet another dependency, but do so in the scope of the previously required file.

At large, this pattern allows you to break your app into multiple small JS files, and load them in an async way to speed up the loading process of web pages.

Some would argue that this is all going to be less needed when SPDY and HTTP2 are going to be more widely used. In any case, this is surely promotes a better modularity in the code design.

like image 73
JAR.JAR.beans Avatar answered Oct 27 '22 20:10

JAR.JAR.beans