When front-end modularization, not only JS needs modular management, but html sometimes also needs modular management. Here we introduce how to implement modular development of html code through requirejs.
How to load html using requirejs
Reuqirejs has a text plug-in that can read the content of a specified file, and the content read is text.
How to download text plugin
The first method can be downloaded through npm:
npm install requirejs/text
The second method can also be downloaded directly from the official github.
Just copy the content directly into text.js.
How to install text plugin
You can configure the dependency of the text plug-in in main.js in requirejs, which is similar to jquery. Just ensure that it can be loaded into it through normal loading.
requirejs.config({baseUrl: './',paths: {'text':path+'/require/text',...},shim: {...}});It can also be placed directly in baseUrl.
How to use text
In the target module, follow the following syntax:
define(function(require){var html = require("text!html/test.html");console.log(html);});or
define(["text!html/test.html"],function(html){console.log(html);});How to carry out modular development of html?
After reading the above, you can already use text, but still don't know how to organize the front-end code.
Take a chestnut:
The website page of the Blog Garden will jump to different pages according to the navigation above. If it is in a single page, it is easy to think of the original method, the navigation button corresponds to a different div. Clicking that button will display the corresponding div; other divs will be hidden.
Then, the front-end code might look like this:
<html><body><nav>Navigation button 1, navigation button 2, navigation button 3</nav><div style="display:block">Page corresponding to button 1</div><div style="display:none">Page corresponding to button 2</div><div style="display:none">Page corresponding to button 3</div></body></html>
Such code will be very messy... and the front-end HTML will be very long...not conducive to maintenance.
Then with the text plugin of reuqirejs, you can do this:
<html><body><nav>Navigation button 1, navigation button 2, navigation button 3</nav><div id="target"></div></body></html>
Then in the corresponding module:
$('#target').html(require("text! target button corresponding to the page.html"));This will make you more casual! Front-end code can also be effectively managed with modules!
However, it should be noted that this method will cause the event bound to be invalid - so you must rebind the event after the html() method.
I will introduce so much to you about using Requirejs for modular development in HTML, and I hope it will be helpful to you!