demand
Recently, I have been maintaining the old project of the company. When I see the code of my predecessors, I have a little doubt about my front-end level. The code of more than ten years ago can not help but make people sigh. Dare not start, even the most basic reading feeling is fast a bit of obstacle, scared to quickly make up for a bad. There is no separation between the front end and the back end of the project. The front end uses JSP to develop the page. The code includes: AngularJS 1.0.0 framework, RequireJS 2.0.0, etc.
1. RequireJS module loader
AMD is the specification of RequireJS asynchronous module definition. One of the most important ideas of AMD asynchronous module loading is to inject dependency, which allows multiple JS files to be injected in the form of array elements in define() function and then used in callback function. This idea was classic in the early days of front-end MVC, and still is.
Asynchronous loading modular JS also known as: AMD, it mainly solves two problems: 1, the need to file modularization, JS file asynchronous loading 2, the need for file dependency, management module dependency, compilation and maintenance require.js: is an asynchronous module loading: AMDCopy the code
2. Basic API usage
Require.js defines three variables: define, require, requirejs. Requirejs: require === requirejs: require is shorter
This API is used to define a module requrie: The requrie() function takes two arguments. The first argument is an array representing the dependent module. The second argument is a callback function that will be executed after the current module is successfully loaded, passing the loaded module to the function as an argumentCopy the code
Define an index. Js
Define (function() {function test() {console.log('index module ')} test()})Copy the code
The define function defines a module that is then used in the page
Require ([' a ']) note: The dependency in reuire is an array. Even if there is only one dependency, you must define it using an array. The second parameter in the require API is the callback function, which is used to process the logic require(['js/a'], Function () {console.log(' I finished loading module A, load finished')})Copy the code
3. Load the file
How do I load a non-native JS library
require.config({ paths:{ 'jquery': [' https://cdn.bootcss.com/jquery/1.10.2/jquery ']}}) requrie ([' jquery '], Function ($) {$(function() {console.log(' Load finished')})}) When loading a third-party remote server or website, require. Config will automatically concatenate the.js address for us, so do not load the.js library address.Copy the code
4, require.js built-in plug-in
1. Run the page DOM deconstruction after loading
Require (['domready!'], function() {console.log('DOM loading complete ')})Copy the code
5,
After learning these, I feel that it is enough. I will continue to read the antique codes of ten years ago. It will be an extraordinary journey.