Home Web Front-end JS Tutorial For the second time, let's talk about the basic knowledge of JS require.js modular tool_javascript skills

For the second time, let's talk about the basic knowledge of JS require.js modular tool_javascript skills

May 16, 2016 pm 03:05 PM
js

Previous article: JS modular tool We introduced requirejs in a very simple way: http://www.jb51.net/article/82527.htm, this article will talk about requirejs Some basic knowledge, including how to use API, etc.

Basic API

require will define three variables: define, require, requirejs, where require === requirejs, generally using require is shorter

define As you can see from the name, this API is used to define a module
require Load dependent modules and execute the callback function after loading
a.js in the previous article:

define(function(){
  function fun1(){
   alert("it works");
  }
  fun1();
})
Copy after login

Define a module through the define function, and then use it in the page:

require(["js/a"]);
To load the module (note that the dependency in require is an array, even if there is only one dependency, you must use an array to define it). The second parameter of the require API is callback, a function that is used to handle the logic after loading. , such as:

require(["js/a"],function(){
  alert("load finished");
})
Copy after login

Load file

In the previous examples, the loaded modules were all local js, but in most cases the JS that needs to be loaded by the web page may come from the local server, other websites or CDN, so it cannot be loaded in this way. We can load a jquery Library as an example:

require.config({
  paths : {
    "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"] 
  }
})
require(["jquery","js/a"],function($){
  $(function(){
    alert("load finished"); 
  })
})
Copy after login

This involves require.config. require.config is used to configure the module loading location. To put it simply, it is to give the module a shorter and easier to remember name. For example, mark Baidu’s jquery library address as jquery, so When requiring, you only need to write ["jquery"] to load the js. We can also configure local js like this:

require.config({
  paths : {
    "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"],
    "a" : "js/a" 
  }
})
require(["jquery","a"],function($){
  $(function(){
    alert("load finished"); 
  })
})
Copy after login

Configuring paths will make our module names more refined. Paths also has an important function, which is to configure multiple paths. If the remote cdn library does not load successfully, you can load the local library, such as:

require.config({
  paths : {
    "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],
    "a" : "js/a" 
  }
})
require(["jquery","a"],function($){
  $(function(){
    alert("load finished"); 
  })
})
Copy after login

After this configuration, when Baidu’s jquery is not loaded successfully, jquery in the local js directory will be loaded

When using requirejs, you do not need to write the .js suffix when loading the module, and of course you cannot write the suffix
The $ parameter is found in the callback function in the above example. This is the output variable of the dependent jquery module. If you depend on multiple modules, you can write multiple parameters in sequence to use:

require(["jquery","underscore"],function($, _){
  $(function(){
    _.each([1,2,3],alert);
  })
})
Copy after login

If a module does not output variable values, then there is none, so try to write the output module in front to prevent misunderstandings caused by misplaced positions

Global configuration

The require.config configuration appears repeatedly in the above example. If the configuration is added to each page, it will definitely look very inelegant. requirejs provides a function called "master data". We first create a main.js :

require.config({
  paths : {
    "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],
    "a" : "js/a" 
  }
})
Copy after login

Then use the following method to use requirejs on the page:


To explain, the script tag that loads the requirejs script adds the data-main attribute. The js specified by this attribute will be processed after reuqire.js is loaded. After we add the require.config configuration to data-main, we can make each All pages use this configuration, and then require can be used directly in the page to load all short module names

data-main also has an important function. When the script tag specifies the data-main attribute, require will default to the js specified by data-main as the root path. What does this mean? For example, after data-main="js/main" is set above, after we use require(['jquery']) (without configuring jquery paths), require will automatically load the js/jquery.js file instead of jquery.js, equivalent to the default configuration:

require.config({
  baseUrl : "js"
})
Copy after login


Third Party Modules

Modules loaded through require generally need to comply with AMD specifications, that is, use define to declare the module. However, sometimes non-AMD standard js needs to be loaded. At this time, another function is needed: shim, and shim is also difficult to explain. Understand, shim is directly translated as "pad", which actually has this meaning. Currently I mainly use it in two places
1. Non-AMD module output, "pad" non-standard AMD modules into available modules. For example: in the old version of jquery, it does not inherit the AMD specification, so you cannot directly require["jquery"]. At this time, A shim is required. For example, if I use the underscore class library, but it does not implement the AMD specification, then we can configure it like this

require.config({
  shim: {
    "underscore" : {
      exports : "_";
    }
  }
})
Copy after login

After configuring this way, we can reference the underscore module in other modules:

require(["underscore"], function(_){
  _.each([1,2,3], alert);
})
Copy after login

For non-AMD modules in the form of plug-ins, we often use jquery plug-ins, and these plug-ins basically do not comply with AMD specifications, such as the jquery.form plug-in. At this time, you need to "pad" the form plug-in into jquery:

require.config({
  shim: {
    "underscore" : {
      exports : "_";
    },
    "jquery.form" : {
      deps : ["jquery"]
    }
  }
})
Copy after login

can also be abbreviated as:

require.config({
  shim: {
    "underscore" : {
      exports : "_";
    },
    "jquery.form" : ["jquery"]
  }
})
Copy after login

这样配置之后我们就可以使用加载插件后的jquery了

require.config(["jquery", "jquery.form"], function($){
  $(function(){
    $("#form").ajaxSubmit({...});
  })
})
Copy after login

好了,requirejs的基本配置大致就是这么多,还有一些扩展的功能会在之后的篇幅中提到,大家不要错过呀!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles