API documentation

Tidy up and accelerate your workflow

Setup

Adding HeadJS to your site

The most common way to include HeadJS on your site will be to include it in the <head>

<html>
    <head>
        <script src="head.min.js"></script>
        <script>
            head.load("file1.js", "file2.js");
        </script>
    </head>
    <body>
        <!-- my content-->

        <script>
            head.ready(function () {
                // some callback stuff
            });
        </script>
    </body>
</html>

But sometimes you might want it to load up a bunch of code right away, without having to declare that code in a new <script> tag. This can be very useful when using code-generation, or even if you just want to stick all your code in a centralized place.

<html>
    <head>
        <script src="head.min.js" data-headjs-load="init.js"></script>
    </head>
    <body>
        <!-- my content-->

        <script>
            head.ready(function () {
                // some callback stuff
            });
        </script>
    </body>
</html>

In the above example you would put your code in init.js, which would be called automagically

// init.js
head.load("file1.js", "file2.js");

Note: Only the first detected instance of data-headjs-load will be used, so make sure there is only one on the page.

Show Comments

Configuration

Sometimes you will want to change how HeadJS behaves by enabling or disabling certain features.

This is the default configuration that HeadJS ships with

conf  = {
    screens   : [240, 320, 480, 640, 768, 800, 1024, 1280, 1440, 1680, 1920],
    screensCss: { "gt": true, "gte": false, "lt": true, "lte": false, "eq": false },
    browsers  : [
                    { ie: { min: 6, max: 11 } }
                    //,{ chrome : { min: 8, max: 31 } }
                    //,{ ff     : { min: 3, max: 26 } }
                    //,{ ios    : { min: 3, max:  7 } }
                    //,{ android: { min: 2, max:  4 } }
                    //,{ webkit : { min: 9, max: 12 } }
                    //,{ opera  : { min: 9, max: 12 } }
    ],
    browserCss: { "gt": true, "gte": false, "lt": true, "lte": false, "eq": true },
    html5     : true,
    page      : "-page",
    section   : "-section",
    head      : "head"
};

If you wanted to change what screen breakpoints HeadJS uses, then you would do something like this

<html>
    <head>
        <script>
            var head_conf = {
                screens: [1024, 1280, 1440, 1680, 1920]
            };
        </script>
        <script src="head.min.js"></script>
    </head>
    <body>
        <!-- my content-->
    </body>
</html>

The same goes for all the other configurable variables. Just make sure var head_conf is declared BEFORE you include HeadJS.

screens
Width breakpoints for which lt,lte,gt,gte,eq can be generated (.gt-800, .lt-1680)
screensCss
Enables/Disables the actual insertion of those breakpoints into the HTML
browsers
Browser/Version breakpoints for which lt,lte,gt,gte,eq can be generated (.ie8, .lt-ie9)
browserCss
Enables/Disables the actual insertion of those breakpoints into the HTML
html5
When enabled, IE8 and less will have the « HTML5 Shim » injected, which adds compatibility for the following HTML5 elements: abbr, article, aside, audio, canvas, details, figcaption, figure, footer, header, hgroup, main, mark, meter, nav, output, progress, section, summary, time, video
page
Suffix used by the « CSS Router » when detecting pages (#v1-page)
section
Suffix used by the « CSS Router » when detecting page sections (.api-section)
head
Name of the variable that should be used for HeadJS. If set to something else like: test, you would call test.load() instead of head.load()

Show Comments

Responsive Design


Browser Information

HeadJS knows certain information about the browser and exposes that information via CSS & JS

These variables are accessible via JavaScript (all the time) so you can apply certain logic depending on specific use-cases

  • head.browser.name (string)
  • head.browser.version (float)
  • head.browser.ie (bool)
  • head.browser.ff (bool)
  • head.browser.chrome (bool)
  • head.browser.ios (bool)
  • head.browser.android (bool)
  • head.browser.webkit (bool)
  • head.browser.opera (bool)
if (head.browser.ie && head.browser.version < 9) {
    /* code specific to IE but only if IE < 9 */
}

The same information is also exposed via CSS, so that you may apply CSS specific fixes

.ie8 {
    /* code specific to IE8 */
}

.lt-ie9 {
    /* code specific to IE but only if IE < 9 */
}

No matter how HeadJS is configured, it will at least generate CSS classes for the current browser & it's version (.ie8, .ff25). Generating classes for (.lt, .lte, .gt, .gte, .eq) including full min/max ranges of browser versions is supported, but not advised since it can generate too much css. By default only current browser + version, and IE6-11 ranges are generated automagically.

You can select which variables are exposed via CSS in the configuration section.

Show Comments

Screen Information

HeadJS also knows information about the current screen & viewport size

These variables are accessible via JavaScript (all the time) so you can apply certain logic depending on specific use-cases

  • head.screen.height (int)
    • This is the height of the screen (resolution) no matter the size of the current browser window
  • head.screen.width (int)
    • This is the width of the screen (resolution) no matter the size of the current browser window
  • head.screen.innerHeight (int)
    • This is the height of the inside of the browser window (viewport), and varies depending on the current size of the browser. It also does not include any eventual menu bars or toolbars. This is the default value when you want to do responsive design !
  • head.screen.innerWidth (int)
    • This is the width of the inside of the browser window (viewport), and varies depending on the current size of the browser. It also does not include any eventual menu bars or toolbars. This is the default value when you want to do responsive design !
  • head.screen.outerHeight (int)
    • This is the height of the entire browser, and varies depending on if the browser is resized or not.
  • head.screen.outerWidth (int)
    • This is the width of the entire browser, and varies depending on if the browser is resized or not.
if (head.screen.innerHeight < 800) {
    /* code specific to VIEWPORT < 800 */
}

Viewport width information is exposed via CSS so you can apply responsive design principles to your website. These have the advantage of working even on browsers that do not support media queries !

.lt-800 {
    /* code specific to VIEWPORT < 800 */
}

.gt-800 {
    /* code specific to VIEWPORT > 800 */
}

You can select which variables (lt, lte, gt, gte, eq) and which breakpoints (480, 640, 800, etc) are exposed via CSS in the configuration section.

Show Comments

Feature Detections

Feature detections help you apply CSS and JS logic depending on what a user supports or not. It also allows you to create custom detection to better manage your site.

Imagine you have a menu or element that's only visible to members

// add the feature
head.feature("member", true);

// use the feature via CSS
.member .member-menu {
    display: block;
}
.no-member .member-menu {
    display: none;
}

// use the feature via JS
if (head.member) {
    // do something
}

You can toggle a feature from one state to another, it's state will be refleted to CSS and JS automatically

In addition to being able to add your custom detections, a bunch of detections are already built in, and they are all accessible via CSS and JS

  • Is the user on a mobile device
    • CSS
      • .no-mobile
      • .mobile
    • JS
      • head.mobile (bool)
  • Is the user on a desktop device
    • CSS
      • .no-desktop
      • .desktop
    • JS
      • head.desktop (bool)
  • Does the usere support touch input
    • CSS
      • .no-touch
      • .touch
    • JS
      • head.touch (bool)
  • Is the users device in portrait mode
    • CSS
      • .no-portrait
      • .portrait
    • JS
      • head.portrait (bool)
  • Is the users device in landscape mode
    • CSS
      • .no-landscape
      • .landscape
    • JS
      • head.landscape (bool)
  • Is the users device a retina display
    • CSS
      • .no-retina
      • .retina
    • JS
      • head.retina (bool)
  • Does the user support CSS Transitions
    • CSS
      • .no-transitions
      • .transitions
    • JS
      • head.transitions (bool)
  • Does the user support CSS3 Transforms
    • CSS
      • .no-transforms
      • .transforms
    • JS
      • head.transforms (bool)
  • Does the user support CSS3 Gradients
    • CSS
      • .no-gradients
      • .gradients
    • JS
      • head.gradients (bool)
  • Does the user support CSS3 Opacity
    • CSS
      • .no-opacity
      • .opacity
    • JS
      • head.opacity (bool)
  • Does the user support Multiple Backgrounds
    • CSS
      • .no-multiplebgs
      • .multiplebgs
    • JS
      • head.multiplebgs (bool)
  • Does the user support CSS3 Box-Shadow
    • CSS
      • .no-boxshadow
      • .boxshadow
    • JS
      • head.boxshadow (bool)
  • Does the user support CSS3 Border-Image
    • CSS
      • .no-borderimage
      • .borderimage
    • JS
      • head.borderimage (bool)
  • Does the user support CSS3 Border-Radius
    • CSS
      • .no-borderradius
      • .borderradius
    • JS
      • head.borderradius (bool)
  • Does the user support CSS Reflections
    • CSS
      • .no-cssreflections
      • .cssreflections
    • JS
      • head.cssreflections (bool)
  • Does the user support CSS3 @Font-Face
    • CSS
      • .no-fontface
      • .fontface
    • JS
      • head.fontface (bool)
  • Does the user support CSS3 RGBA
    • CSS
      • .no-rgba
      • .rgba
    • JS
      • head.rgba (bool)

Show Comments

HTML5 Shim

Target HTML5 and CSS3 elements safely

Want to start using HTML5 semantics but are put off by it because you still have a large audience of users using non compatible browsers ?

DIV's are good, but HeadJS let's you be semantic and futuristic

/* Use CSS3 semantics */
<style>
    article { text-shadow:0 0 1px #ccc; }
</style>
 
<!-- works in IE too -->
<article>
    <header></header>
    <section></section>
    <footer></footer>
</article>

HeadJS will detect if IE < 9 is present, and inject the necessary HTML5 Shim for you.

You will still need to use a HTML5 enabling stylesheet for it to work like Normalize.css, or just download our file and reference it in your HEAD.

<html>
    <head>
        <link rel="stylesheet" href="html5.min.css" />
        <script src="head.min.js"></script>

        /* Use CSS3 semantics */
        <style>
            article { text-shadow:0 0 1px #ccc; }
        </style>
    </head>
    <body>
        <!-- works in IE too -->
        <article>
            <header></header>
            <section></section>
            <footer></footer>
        </article>
    </body>
</html>

You can also enable/disable the injection via the configuration section.

---

But before you start believing all the hype around HTML5, be sure to give this a read ..you'll be surprised !

The Truth About HTML5
The Truth About HTML5

Show Comments

CSS Router

Know which page & section the user is currently on and react accordingly

Ever need to highlight or change certain features depending on where the user is ? HeadJS will detect the current page, and what section (subfolder/path) the user is on, and generate CSS classes that you can then easily target.

  • page (..problem with decimals ? should we drop, concenate ?)
    • Will generate a CSS id for the current page: #v1-page
  • section
    • Will generate multiple CSS classes for the current path: .site-section, .api-section
/* user is on any page that ends with /index.* or on the root path / or */
#index-page .main-menu {
    background-color: gray;
}

/* user is on a path containing /api/ */
.api-section .top-menu {
    display: none;
}

/* mix & match */

/* for example the user is on /api/test.html */
#test-page.api-section .top-menu {
    display: block;
}

If the user is on page « /home/api/test.html » HeadJS will generate the following CSS classes for you: #test-page, .home-section, .api-section

You can choose how these variables are named in the configuration section.

Show Comments

Document Ready

Know when the document or various files have finished loading

The best way to not block rendering of a page is to not put JS all over the page. The best practice is to put all your CSS in the <head> and all your JS right before the </body>

Unfortunately this is not always possible, since often various elements depend on certain JS before getting to the </body>. To work around this we can push functions downwards to be able to execute them later when all the JS has finished loading.

<html>
    <head>
        <script src="head.min.js"></script>
        <script>
            // this loads jquery asyncrounously & in parallel
            head.load("jquery.min.js");
        </script>
    </head>
    <body>
        <!-- some content-->

        <!-- injected via a module or an include -->
        <script>
            // some function that depends on jquery
            head.ready("jquery.min.js", function () {
                // this will only be executed once jquery has finished loading
                $(".main").hide();
            });
        </script>

        <!-- some content-->
    </body>
</html>

Even when not depending on something like jQuery, if we should have inline scripts, it is always faster and safer to push the execution of those scripts to the bottom.

<html>
    <head>
        <script src="head.min.js"></script>
    </head>
    <body>
        <!-- some content-->

        <!-- injected via a module or an include -->
        <script>
            // schedule the execution of the function for later
            // when the rest of the document has finished loading
            head.ready(document, function () {
                // some big function
            });
        </script>

        <!-- some content-->
    </body>
</html>

head.ready() takes the following arguments

// Attention: subtility here
head.ready(function() {
    // push a function to the end of the page for later execution
    // runs once all files have finished loading
    
    // WARNING: if no files are cued for loading this will NOT trigger !
});

head.ready(document, function() {
    // push a function to the end of the page for later execution
    // runs as soon as the document is ready
});

head.ready("file1.js", function() {
    // execute this function, only when file1.js has finished loading
    // used in conjunction with head.load("file1.js");
});

head.ready(["file1.js", "file2.js"], function() {
    // execute this function, only when file1.js AND file2.js has finished loading
    // used in conjunction with head.load("file1.js", "file2.js");
});

head.ready("label1", function() {
    // execute this function, only when label1 has finished loading
    // used in conjunction with head.load({ label1: "file1.js" });
});

head.ready(["label1", "label2"], function() {
    // execute this function, only when label1 AND label2 has finished loading
    // used in conjunction with head.load([{ label1: "file1.js" }, { label2: "file2.js" }]);
});

Show Comments

Resource Loading

Speed up your site. Manage your library's dependencies. Load javascript and stylesheets in parallel but execute them in the correct order.

Resource loading has many different options to cater to various needs

// queue scripts and fire a callback when loading is finished
head.load("file1.js", "file2.js", function() {
    // do something
});

// same as above, but pass files in as an Array
head.load(["file1.js", "file2.js"], function() {
    // do something
});
                                                         
// you can also give scripts a name (label)
head.load({ label1: "file1.js" }, { label2: "file2.js" }, function() {
    // do something
});

// same as above, but pass files in as an Array
head.load([{ label1: "file1.js" }, { label2: "file2.js" }], function() {
    // do something
});                   

// Labels are usually used in conjuntion with: head.ready()
head.ready("label1", function() {
    // do something
});

// Actually if no label is supplied, internally the filename is used for the label
head.ready("file1.js", function() {
    // do something
});

All the above examples also work with CSS files.

// queue scripts and fire a callback when loading is finished
head.load("file1.css", "file2.css");

// same as above, but pass files in as an Array
head.load(["file1.css", "file2.css"]);

Conditional Loading

You can also run tests to load file A if a test succeeds, or fallback to file B. This is great for loading Polyfils, or loading dependencies when certain conditions are met.

// signature
head.test(condition, success, failure, callback);

/*
    condition: something that evaluates to true/false
    success  : a file, an array of files, a labeled object, an array of labeled objects
    failure  : a file, an array of files, a labeled object, an array of labeled objects
    callback : a function to call when evaluation & loading is done
*/


// simplified version 1
head.test(condition, "success.js", "failure.js" , callback);

// simplified version 2
head.test(condition, ["success1.js", "success1.js"], "failure.js" , callback);   

// object version
head.test({
    test    : bool,
    success : ["file1.js", "file2.js"],
    failure : ["poly1.js", "poly2.js"],
    callback: function() {
        // do stuff     
    }
);

// Example
head.test(head.mobile, "normal.js", "fallback.js", function() {
    // do stuff
});

Show Comments



Make it the only script in your HEAD. « A concise solution to universal problems »

head.ready(?)

Api Documentation

Documentation

Download

Download
 
 
Top