My 5th book "50 Tips on JavaScript" is on sale. Go get it from https://50tips.dev.
Illustrated guide to 50 of the most interesting JavaScript topics.

Insert css or javascript dynamically

That's a super simple function for adding new css or javascript files in the current document. I didn't test it in all the browsers, because I'm using it in the chrome extension and I need only Chrome supported.
var injectFiles = function(files, callback) {
  var filesLoaded = 0;
  var parent = document.querySelector("body") || document.querySelector("head");
  var onFileLoaded = function() {
    if(++filesLoaded == files.length) {
      callback();
    }
  }
  for(var i=0; iUsage:
injectFiles(["css/styles.css", "js/vendor/jquery.js"], function() {
     // do some other stuff here
});
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. To leave a comment go here.