This blog post is served as my copy-and-pasting some snippets for dynamically loading JavaScript and CSS files. I found myself quite often posting with external JavaScript and CSS files. So, this would help me to just copy the function and use it to load the file.

The following code is a snapshot, see the latest version on Gist.


// Code snippets for dynamically loading JavaScript and CSS
// Copyright : This script has been placed in the public domain.
// Gist : https://gist.github.com/livibetter/5211293
// Blog post : https://yjlv.blogspot.com/2013/03/dynamically-loading-javascript-and-css.html
// Last update : 2013-03-21T07:35:25Z
// Author : Yu-Jie Lin
// Website : http://yjl.im

function load_CSS(src, cb) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = src;
if (cb) {
link.addEventListener('load', cb);
}
document.getElementsByTagName('head')[0].appendChild(link);
}

function inject_CSS(css, cb) {
var style = document.createElement('style');
style.innerHTML = css
if (cb) {
style.addEventListener('load', cb);
}
document.getElementsByTagName('head')[0].appendChild(style);
}

function load_JS(src, cb) {
var script = document.createElement('script');
script.src = src;
if (cb) {
script.addEventListener('load', cb);
}
document.getElementsByTagName('head')[0].appendChild(script);
}

1   Functions

  • load_CSS and load_JS: first argument is the source URL and second is the callback function when the file is loaded.

    Note that in Firefox, maybe also in other browsers, CSS file’s MIME type has to be text/css, see Incorrect MIME Type for CSS Files. That being said, if you try to load the raw URL of CSS files on Gist or GitHub—which returns with text/plain, it won’t work. You must load the file from GitHub Pages.

  • inject_CSS: first argument is the CSS text and second is the call back function when the CSS is loaded.

2   Note

I wrote them from scratch, so I could place them in Public Domain and you can feel free to use it in whole or partially. They don’t require additional library, that should be good, even though they may be little longer.

I know there may be some issues with different browsers and versions, I only briefly tested in Firefox. Feel free to let me know if you encounter any issues, or to fix it on Gist and give me a nudge, so I can pull your patched code. But be sure you also agree to put your modifications in public domain when you contact me about the changes you made.