Abhishek Yadav
ரூபீ ப்ரோக்ராமர்
Co-organizer: Chennai.js and Chennai.rb
Turbolinks
Turbolinks
Turbolinks
Turbolinks Demo
Turbolinks
http://pjax.herokuapp.com
Turbolinks
Turbolinks
Turbolinks
Turbolinks
Turbolinks
Turbolinks
Listen on the turbolinks:load event
Use event delegation
Use MutationObserver
Turbolinks
Use turbolinks:load
After loading a new page, Turbolinks fires the turbolinks:load event. All/most $(document).ready can be replaced with that -
$(document).ready(function(){
// page load stuff
})
// becomes
$(document).on("turbolinks:load", function(){
// page load stuff
})
// or
document.addEventListener("turbolinks:load", function() {
// page load stuff
})
Turbolinks
Listening on turbolinks:load is not the best approach.
Turbolinks
Event delegation
Turbolinks
Event delegation
// Instead of -
$('.dance-button').on('click', function(){
// start dancing
})
// This -
// Will work if .dance-button is loaded later by an Ajax call
// Will work with Turbolinks without change
$('body').on('click', '.dance-button' function(){
// start dancing
})
Turbolinks
Mutation Observers
Turbolinks
var el = document.getElementById('#my-widget');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
console.log("It changed");
});
observer.observe(el, { childList: true })
Mutation Observers
Turbolinks
Opt out
Cache will not be used in restoration (back button)
or for previews (for visited links)
<meta name="turbolinks-cache-control" content="no-cache">
Turbolinks
Persist elements
<div id="cart-counter" data-turbolinks-permanent>1 item</div>
Turbolinks
Idempotent scripts
Scripts that can be run one or many times with the same result
// Overscripting example -
// This is an inline script
<script>
function foo(){
$("#welcome").append("<b> Welcome to our site </b>");
}
function bar(){
$("#welcome").html("<b> Welcome to our site </b>");
}
foo();
bar();
</script>
// foo is not-idempotent
// bar is idempotent
Turbolinks
Turbolinks
Why resist client-side Js frameworks - cons
Turbolinks
Why resist client-side Js frameworks - pros
Turbolinks