lucasarruda
lucasarruda

Reputation: 1482

Turbolinks load event doesn't work on page load

I'm having an issue with current default turbolinks recommended load event:

document.addEventListener('turbolinks:load', function() {
  …
});

What happens is that this doesn't fire on Safari when page is loaded. Therefore I appended Turbolinks.dispatch("turbolinks:load"); to application.js.

It seemed to work fine. But on Chrome, it did fire automatically, so what it ended up happening is a double-fire of turbolinks:load event.

My first fix was to fire turbolinks:load only on non-Chrome browsers.

But somehow, even on Chrome, some of the views don't trigger turbolinks:load automatically. So I ended up having to fire it on specific views too.

The final solution I found was to use:

$(document).on('ready turbolinks:load', function() {
  …
});

This seems to fix all the issues because it fires on first page load or reload and when I click links. It also fires on Chrome and Safari.

Is there a better way to handle this?

Docs say that first version is correct, but that doesn't seem to be the case.

Am I missing something?

(note: using jQuery is not a downside for me and I know I could implement that with a couple of document.addEventListener)

Upvotes: 4

Views: 6631

Answers (1)

Dom Christie
Dom Christie

Reputation: 4240

As noted in the comments, you are loading the Turbolinks with async. Turbolinks currently does not work well when loaded asynchronously. So the best advice at the moment is to remove the async attribute from the script tag, or use defer instead.

Why?

Turbolinks listens out for the DOMContentLoaded event on the first load to then trigger turbolinks:load. By loading it asynchronously, it's possible that the script finishes loading/executing after the HTML has been parsed and DOMContentLoaded fired. In this case, turbolinks:load will not be fired.

There is currently a GitHub issue to discuss some possible solutions for the library to implement: https://github.com/turbolinks/turbolinks/issues/281

Upvotes: 4

Related Questions