michael hue

Hi! My name is Michael Hüneburg. I'm a Web Developer and Interface Designer based in Hannover, Germany.

I'm the co-founder of Think + Craft.

Shoot me an Email if you like, but definitely follow me on Twitter.

Using HTML5’s data attribute to pass settings to external JavaScript

Whew, what a headline. It’s actually a very simple technique I stumbled on recently while refactoring my “network” script (the navigation thingy in the upper right corner).

So, what is this about? Let’s assume you have a JavaScript file which is used on several websites. On each site you want to be able to pass one or more variables to the script to customize it. The traditional way would be something like this (note that this is HTML5 syntax which doesn’t require the type attribute):

<script>
var settings = {
    style: 'light',
    position: 'topright'
};
</script>
<script src="http://example.org/foo.js"></script>

This has two main disadvantages:

  1. You need to create a variable inside the global namespace which could cause conflicts with other scripts.
  2. The code looks very cluttered.

Fortunately the HTML5 data attribute is here to help. What does it do?

“Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.”

Perfect. We can use this to configure our JavaScript right inside the script tag that includes it. Here we go:

<script src="http://example.org/foo.js" data-style="light" data-position="topright"></script>

The only thing we need now is some code that extracts the configuration from the matching script tag. I’m using jQuery here in order to keep it simple:

var script, settings;

script = $('script[src$="foo.js"]');
options = {
    style: script.data('style'),
    position: script.data('position')
};

We’re using the “attribute ends with” selector to fetch the right script tag and extract the data attributes with jQuery’s .data() function (requires version 1.4.3 or newer). Be sure to change the src$="foo.js" part when using the code in your own scripts.

And that’s all there is to it. I don’t know if it has been done before but I found that to be an elegant technique to keep your code and global namespace clean.