Home  >  Article  >  Web Front-end  >  A brief introduction to RequireJS and how to use it

A brief introduction to RequireJS and how to use it

高洛峰
高洛峰Original
2016-12-09 15:37:351135browse

Introduction to RequireJS

RequireJS is a JavaScript module loader. It's great for use in the browser. Using RequireJS to load modular scripts will improve the loading speed and quality of your code.

Compatibility

A brief introduction to RequireJS and how to use it

Advantages

Realize asynchronous loading of js files to avoid web pages losing response

Manage dependencies between modules to facilitate code writing and maintenance

Get started quickly

step 1

Introduction The dependency in require.js

require() is an array. Even if there is only one dependency, you must use an array to define it

The second parameter is the callback function (callback), which can be used to resolve dependencies between modules

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="require.js"></script>
    <script type="text/javascript">
      require(["js/a"], function(){
        alert("load finished");
      });
    </script>
  </head>
  <body>
   body
  </body>
</html>

step 2

require.config is used to configure the module loading location

If the fixed location is relatively long, you can use baseUrl: "js", then there is no need to write js in paths

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="require.js"></script>
    <script type="text/javascript">
      require.config({
        paths : {
          "jquery" : ["http://vs.thsi.cn/js/jquery-1.7.2.min", "js/jquery"],
          "a" : "js/a"       
        }
      });
 
      require(["jquery", "a"], function(){
        alert("load finished");
      });
    </script>
  </head>
  <body>
   body
  </body>
</html>

step 3

The require.config configuration appears repeatedly in step 2. If the configuration is added to each page, it will not be good. requirejs provides a function called "master data"

Create a main .js Put the require.config in step 2 into main.js

<script data-main="js/main" src="js/require.js"></script>

step 4

Modules loaded through require generally need to comply with AMD specifications, that is, use define to declare the module, but sometimes it is necessary to load non- AMD standard js, you need to use another function at this time: shim

require.config({
  shim: {
    "underscore" : {
      exports : "_";
    },
    "jquery.form" : ["jquery"]
  }
});
require(["jquery", "jquery.form"], function($){
  $(function(){
    $("#form").ajaxSubmit({...});
  })
});


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn