The first and second sections of this series introduce JavaScript module prototypes and theoretical concepts, and today we describe how they can be used in combat.
I'm using a very popular library require.js.
One, why should use Require.js?
At the earliest, all of the JavaScript code was written in a file, and it was enough to load the file. Later, more and more code, a file is not enough, must be divided into multiple files, sequentially loaded. The following page code, I believe many people have seen.
<script src= "1.js" ></script>
<script src= "2.js" ></script>
<script src= "3.js" ></script>
<script src= "4.js" ></script>
<script src= "5.js" ></script>
<script src= "6.js" ></script>
This code loads multiple JS files sequentially.
There are a lot of drawbacks to this way of writing. First of all, when loading, the browser will stop the page rendering, the more loading files, the longer the page will lose the response time, and secondly, because the JS file dependencies, Therefore, we must strictly ensure the loading sequence (such as the above example of the 1.js to be in front of 2.js), the most dependent module must be put to the last load, when the dependency is very complex, code writing and maintenance will become difficult.
The birth of require.js is to solve these two problems:
(1) To realize the asynchronous loading of JS files to avoid web page loss of response;
(2) Management of the dependencies between modules, easy to write code and maintenance.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/