kubetail-org / loadjs

A tiny async loader / dependency manager for modern browsers (899 bytes)
MIT License
2.57k stars 149 forks source link

Ability to insert elements after or before certain element #90

Closed mbvyd closed 5 years ago

mbvyd commented 5 years ago

(Almost) same feature which has https://github.com/filamentgroup/loadCSS ("Function API" section, "before" param).

Possible use case: In head section may be placed call to loadjs to load external CSS (example below). At the same time may be needed to load bunch of js, which should be loaded and applied synchronously. And it is more than ok to place them before </body>.

Of course, it is possible to exclude those scripts from processing by loadjs. But with control of where (when) to load elements we could manage all stuff in one control script:

// load CSS as soon as possible
loadjs([
    '/assets/css/bootstrap.css', 
    '/assets/css/animate.css', 
    '/assets/css/styles.css'
], 'cssCore', {
    async: false
}); 

// load js preferably at the bottom of HTML code to speed up loading of page; 
// with current setup calls to synchronous scripts 
// will be placed in <head> section of markup:
loadjs.ready('cssCore', function() {
    loadjs([
        '/assets/site/js/jquery-3.2.1.min.js',
        '/assets/site/js/owl.carousel.min.js',
        '/assets/site/js/core.js'
    ], 'jsCore', {
        async: false
    });
}); 

// execute non-critical js after base js is ready as it depends on it
loadjs.ready('jsCore', function() {
    // do some js stuff 
});
amorey commented 5 years ago

You can do a custom insert using the before callback:

loadjs(['/path/to/foo.js', '/path/to/bar.css'], {
  success: function() {},
  error: function(pathsNotFound) {},
  before: function(path, scriptEl) {
    if (path === '/path/to/foo.js') {
      document.body.appendChild(scriptEl);
      return false;  // return false to bypass default DOM insertion mechanism
    }
  }
});
mbvyd commented 5 years ago

Thanks, i missed this