Preface
Recently, the project has a requirement: HTML pages can generally be composed of CSS, JavaScript, Dom (usually Div), and some JS page initialization functions, now we need to split a page into four parts: CSS, JavaScript, Dom, and JS init functions. We can obtain these four parts from the server and render the complete page after splicing them together. CSS and DOM nodes are easy to process, but many problems need to be taken into account for JavaScript loading and JS init execution. If someone encounters a similar problem, you can discuss it. After all, there will be many problems if you want to build a perfect framework. In this article, I will introduce some practices for loading and managing JavaScript and hope to help you.
Native JavaScript implementation
This provides a solution for friends who do not want to use the framework.
function loadScript(url, callback) { var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState) { //IE script.onreadystatechange = function () { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function () { callback(); }; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script);}
Lab implementation
$LAB.setOptions({ AlwaysPreserveOrder: true}).script("script1.js") // script1, script2, script3, and script4 *DO* depend on each .script("script2.js") // other, and will execute serially in order after all 4 have have.script("script3.js") // loaded in parallel.script("script4.js").wait(function () { initFunction();});
$LAB.setOptions({ AllowDuplicates: true}).script("script1.js").wait().script("script2.js").script("script3.js").wait().script("script4.js").wait(function () { initFunction();});
Requirejs implementation
(function (require) { var urlArgs = ''; // used for browser cache if (CNBlogs.isProduct) { urlArgs = 'v=1'; } else { urlArgs = "dev=" + (new Date()).getTime(); } require.config({ baseUrl: '/scripts', //By default load any module IDs from baseUrl urlArgs: urlArgs, paths: { 'hello1': 'hello1.min', 'hello2': '/document/11111-11100-010101/latest?' // append ? to avoid .js extension }, shim: { 'hello3': ['hello1', 'hello2'], 'hello4': ['hello3', 'bootstrap'] }, waitSeconds: 200 });})(require);require(['jqueryui', 'hello4'], function () { initFunction();});
References
Labjs official documentation: http://labjs.com/documentation.php
Requirejs official documentation: http://requirejs.org/docs/api.html
Follow-up
Labjs and requirejs are not absolutely bad. It is only convenient to see which one you are using. Many questions in this article are not described in detail. If you have any questions, contact and discuss with each other.
QQ: 1321518080