mwbrooks / thumbs.js

Add touch support to your browser with thumbs.js - a small, transparent, and syntax-less library.
http://mwbrooks.github.com/thumbs.js/
MIT License
318 stars 36 forks source link

Not working when loaded after document-load event has been fired #14

Closed jeppester closed 11 years ago

jeppester commented 11 years ago

As by now, the script requires a document-load event to be fired before it will work. This makes the script unusable for situations where you would like to add thumbs.js to an already loaded document.

A simple fix for this, would be to wrap the initialization inside a check of the document's readystate.

Instead of the current window.addEventListener-call, it could be something like this:

var init = function() {
    for (var key in eventMap) {
        document.body.addEventListener(key, function(e) {
            // Supports:
            //   - addEventListener
            //   - setAttribute
            var event = createTouchEvent(eventMap[e.type], e);
            e.target.dispatchEvent(event);
            // Supports:
            //   - element.ontouchstart
            var fn = e.target['on' + eventMap[e.type]];
            if (typeof fn === 'function') fn(e);
        }, false);
    }
}

if (document.readyState == "complete" || document.readyState == "loaded") {
    init()
}
else {
    window.addEventListener('load', init, false)
}
mwbrooks commented 11 years ago

@jeppester

Awesome suggestion and I'm down for adding this to thumbs.js. I should have a free moment this weekend to update the code.

jeppester commented 11 years ago

Sounds great!

Awesome polyfill by the way.

mwbrooks commented 11 years ago

Released as 0.6.0. Thanks a load @jeppester!