I am using SmoothState.js for page transitions and it works fine and loads the new pages with ajax. However, I have JS scripts on each page that need to be reinitialized and I have not been able to get them to always be present on page transitions.
Based on the FAQ:
smoothState.js provides the onAfter callback function that allows you to re-run your plugins. This can be tricky if you're unfamiliar with how AJAX works.
When you run a plugin on $(document).ready(), it's going to register only on elements that are currently on the page. Since we're injecting new elements every load, we need to run the plugins again, scoping it to just the new stuff.
A good way to do this is to wrap your plugin initializations in a function that we call on both $.fn.ready() and onAfter. You'll want to specify the context each time you initialize the plugins so that you don't double-bind them. This is called a "module execution controller".
What my plan has been is to take the functions from my JS files and put them all into an onAfter call inside the SmoothState.js file. That way each time a user changes page, the functions would always be available.
Here the code structure I have now. I've done a lot of digging but I am stuck. Can you help me figure out what I am doing wrong? Thanks for your time!
$(document).ready(function() {
mail();
});
$('#main').smoothState({
onAfter: function() {
mail();
}
});
function mail() {
// script from mail.js goes here
}
$(function() {
$('#main').smoothState();
});
$(function() {
"use strict";
var options = {
prefetch: true,
pageCacheSize: 3,
onStart: {
duration: 250, // Duration of our animation
render: function($container) {
// Add your CSS animation reversing class
$container.addClass("is-exiting");
// Restart your animation
smoothState.restartCSSAnimations();
}
},
onReady: {
duration: 0,
render: function($container, $newContent) {
// Remove your CSS animation reversing class
$container.removeClass("is-exiting");
// Inject the new content
$container.html($newContent);
}
},
},
smoothState = $("#main").smoothState(options).data("smoothState");
});