scottjehl / Respond

A fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)
MIT License
11.33k stars 3.37k forks source link

How to create a custom event listener for Respond.js #343

Open huunguyendac opened 9 years ago

huunguyendac commented 9 years ago

I want run script after respond loaded. but not solution. I try setTimeout but it not good solution. thank all

mynamesleon commented 8 years ago

I know you asked this ages ago, but I wanted to do the same thing recently, so thought I'd reply with my solution. I had to edit the original source file though.

The bulk of the work is triggered by the makeRequests function. So I edited it to this:

makeRequests = function () {
    if (requestQueue.length) {
        var thisRequest = requestQueue.shift();
        ajax(thisRequest.href, function(styles) {
            translate(styles, thisRequest.href, thisRequest.media);
            parsedSheets[thisRequest.href] = true;
            w.setTimeout(makeRequests, 0);
        });
    } else {
        if (typeof respond.onComplete === 'function') {
            respond.onComplete();
        }
    }
}

The requestQueue.length conditional and its contents already exist in the source code, so this is just tying into that. So if no more requests need to be made, we trigger an onComplete method on the respond object (if it exists, and is a function).

Then, after respond.js has been loaded in (whether you're doing the asynchronously, or through a standard script tag), in your own script file you can include everything you need in the onComplete function. Personally, I use it to trigger a custom jQuery event which I can re-use:

if (typeof window.respond !== 'undefined') {
    window.respond.onComplete = function () {
        $(window).trigger('respondReady');
    };
}

Then, if I have lots of different sections of code that I need to trigger once respond has finished, I just use:

$(window).on('respondReady', function () {
    // do something
});