Where to put the page-initialize javascript when using pjax?

larryzhao picture larryzhao · Mar 14, 2012 · Viewed 8.2k times · Source

Most of the times, I put some javascript code in $(document).ready to do some initialization stuffs on the page, like event binding, etc.

But now I would like to use pjax https://github.com/defunkt/jquery-pjax for some of my pages.

With pjax, because there's only part of the page gets refreshed, $(document).ready will not get called again.

I could manually trigger the initializing script on event pjax:end, but I also want to know if there's a better solution for that.

Thanks.

Answer

Adrian Macneil picture Adrian Macneil · May 16, 2012

You can easily link all your existing code to both the document.ready and pjax:success events, like so:

Before:

$(document).ready(function() {
    // page load stuff
});

After:

$(document).on('ready pjax:success', function() {
    // will fire on initial page load, and subsequent PJAX page loads
});