author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

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) {
  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. Or maybe comment below: