Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
huunguyendac opened this issue Sep 18, 2015 · 1 comment
Open

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

huunguyendac opened this issue Sep 18, 2015 · 1 comment

Comments

@huunguyendac
Copy link

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

@mynamesleon
Copy link

mynamesleon commented May 18, 2016

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
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants