Cách hoạt động của các module loader? (ok) một ví dụ kinh điển :)

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="loader.js"></script>
</head>
<body>
	Loader
</body>
</html>

loader.js

(function() {
  var libs = new Array;
  var styles = new Array;
  //Xác định URL của thư viện cần dùng, ở đây tôi dùng WOWjs, sử dụng WOWjs yêu cầu 2 dependencies là jQuery và animate.css
  libs[0] = 'https://code.jquery.com/jquery-1.12.4.js';
  libs[1] = 'https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.js';
  styles[0] = 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css';
  core = 'main.js';
  //Vòng lặp để gửi request thư viện
  for (let i = 0; i < libs.length; i++) {
    //Sử dụng Promise để xử lý khi có kết quả trả về
    libs[i] = new Promise((resolve, reject) => {
      let xhttp = new XMLHttpRequest();
      xhttp.open("GET", libs[i], true);
      xhttp.onload = function() {
        //Nếu request tài nguyên thành công, tạo 1 thẻ script và append code vào
        if (this.readyState == 4 && this.status == 200) {
          let script = document.createElement('script');
          script.innerHTML = this.responseText;
          let body = document.getElementsByTagName('body')[0];
          body.appendChild(script);
          resolve();
        }
      }
      xhttp.send();
    });
  }
  for (let i = 0; i < styles.length; i++) {
    styles[i] = new Promise((resolve, reject) => {
      let xhttp = new XMLHttpRequest();
      xhttp.open("GET", styles[i], true);
      xhttp.onload = function() {
        if (this.readyState == 4 && this.status == 200) {
          let style = document.createElement('style');
          style.innerHTML = this.responseText;
          let body = document.getElementsByTagName('body')[0];
          body.appendChild(style);
          resolve();
        }
      }
      xhttp.send();
    });
  }
  //Khi tất cả các dependencies đã load xong, thực thi code chương trình
  Promise.all(libs.concat(styles)).then(() => {
    console.log('Initialized !!!');
    let xhttp = new XMLHttpRequest();
    xhttp.open("GET", 'main.js', true);
    xhttp.onload = function() {
      if (this.readyState == 4 && this.status == 200) {
        let style = document.createElement('script');
        style.innerHTML = this.responseText;
        let body = document.getElementsByTagName('body')[0];
        body.appendChild(style);
      }
    }
    xhttp.send();
  })
})();

main.js

new WOW().init();
var element = $('body').append('<h1 class="wow bounceInUp" style="text-align: center">Welcome to Module Loader</h1>');

Last updated

Navigation

Lionel

@Copyright 2023