needs to add a parameter&nbs"/> needs to add a parameter&nbs">

Home  >  Article  >  Web Front-end  >  How to use require.js? Make JS load faster

How to use require.js? Make JS load faster

PHP中文网
PHP中文网Original
2017-06-21 10:59:391765browse

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;
    }; 
});

//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>

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)]
    }; 
});

//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>

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!

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