I wrote a test code and used require.js to work with a plug-in text.js to implement the simplest single-page application. It can be recorded easily and facilitate future review.
git address: https://github.com/lily1010/requireSPA
Let's take a look at the directory below
As can be seen from the above project, I extracted css separately and implemented on-demand loading, that is, test1.css will be loaded when test1.html is loaded, and test2.css will be loaded when test2.html is loaded.
1. Let’s look at the entry index.html code first
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title></title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <style type="text/css"> </style> </head> <body> <script data-main="js/main" src="js/require.js"></script> <div> </div> </body></html>
The above is very simple. First define the requirejs entry data-main. In addition, in order to load css on demand, I defined a class css-attribute.
2. Configure the path and do logical processing in main.js
require.config({ paths:{ "jquery":"lib/jquery-1.11.0", "text":"lib/text", "text1":"../template/test1.html", // Pay attention to the path "text2":"../template/test2.html", "css1":"../style/test1.css", "css2":"../style/test2.css" }}) require(['jquery','text!text1','text!text2','text!css1','text!css2'],function($,template1,template2,css1,css2){// Enter the page and set it to page test1.html content $(".css-attribute").html(css1); $(".page").html(template1); // Click the skip button to set it to page test2.html content $(".skip").click(function(){ $(".css-attribute").html(css2); $(".page").html(template2); })})The above are the most basic require configuration, just pay attention to the usage of text.js, it's very simple
3. Let’s take a look at the two page structures and styles
①The test1.html code is as follows:
<div><button>Click me to jump to the second page of the SPA</button></div>
②The css of test1.html, that is, test1.css code is as follows:
.test1{ position: absolute; top:0; bottom:0; left: 0; right: 0; background-color: red;}.skip{ position: absolute; top:50%; left: 50%; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);}The effect is as follows:
③The test2.html code is as follows:
<div> <button>I am the second page, click me to go back to the first page</button></div>
④The css of test2.html, that is, test2.css code is as follows:
.test2{ position: absolute; top:0; bottom:0; left: 0; right: 0; background-color: pink;}.skip2{ position: absolute; top:50%; left: 50%; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);}The effect is as follows:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.