Home > Web Front-end > JS Tutorial > body text

How to use require.js? Make JS load faster

PHP中文网
Release: 2017-06-21 10:59:39
Original
1831 people have browsed it

When a webpage introduces many js files, the loading of the webpage will become very slow, and the js files have dependencies. Sometimes they cannot be run if they are reversed in order, which greatly affects the user experience.

require.js solves the problem of asynchronous loading and improves the loading of web pages. At the same time, js that relies on order can be sorted by arrays.

The first part loads require.js and puts it in the js subdirectory of the directory:

<script src ="js/require.js?1.1.10">script>

Need to add a parameter defer async="true" means this The file needs to be loaded asynchronously defer compatible with IE version


Need to add data-main="js/main" to indicate that main.js under js is the main load module. You must be rigorous when working.


require() function accepts two parameters. The first parameter is an array, indicating the modules it depends on, and the second parameter is the return function, which will be called after all the previous modules are loaded successfully.

//main.js:

define(function (require,exports,module){
    exports.add = function (x,y){
      return x+y;
    }; 
});
Copy after login

//math.html:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script src="require/require.js?1.1.10"></script><script>require(['main'], function (math){
            alert(math.add(1,1));
              });</script></head><body></body></html>
Copy after login

Returns a 2, indicating success pop up.

Call together

//b.js:

define(function (require,exports,module){
    exports.add = function (obj,oEv,show){
      return obj[addEventListener(oEv,show,false)]
    }; 
});
Copy after login

//math.html:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script src="require/require.js?1.1.10"></script><script>var btn=document.getElementById('btn');function show(){
                alert('弹出')
            }
            require(['main','main'], function (math){
               math.add(btn,'click',show);
                alert(math.add(1,1));
              });</script></head><body><button id="btn">提交</button></body></html>
Copy after login

Read this article, please leave a message if there is anything wrong.

The above is the detailed content of How to use require.js? Make JS load faster. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template