$ variable losing values after turbo request
Closed this issue · 1 comments
October version: dev-develop
I noticed a strange issue where the $ variable is losing values on turbo requests (for example $.request becomes undefined after clicking on a turbo link). The easiest way to replicate the issue is to create 2 simple pages:
Page 1:
title = "Page 1"
url = "/page-1"
==
<html>
<body>
<h1>PAGE 1</h1>
<a href="/page-2">Open page 2</a>
<script src="{{ ['@jquery', '@framework.bundle'] | theme }}"></script>
<script>console.log($.request);</script>
</body>
</html>
Page 2:
title = "Page 2"
url = "/page-2"
==
<html>
<body>
<h1>PAGE 2</h1>
<a href="/page-1">Open page 1</a>
<script src="{{ ['@jquery', '@framework.bundle'] | theme }}"></script>
<script>console.log($.request);</script>
</body>
</html>
Now click multiple times on links Open page 1
/ Open page 2
and you get the following output in the console:
The strange thing is that if I put the first script tag in the <head>
of the document then everything works ok. But if it's at the bottom (as best practices dictate) then the issue is there.
Hey @acasar
This likely occurs because the framework is re-evaluated on render, and it loses context.
Consider placing the scripts in the <head>
tag and using <script defer>
instead (1). Otherwise, you'll need to instruct the turbo router not to evaluate the script on PJAX load with data-turbo-eval="false"
(2).
Option 1
title = "Page 1"
url = "/page-1"
==
<html>
<head>
<script defer src="{{ ['@jquery', '@framework.bundle'] | theme }}"></script>
</head>
<body>
<h1>PAGE 1</h1>
<a href="/page-2">Open page 2</a>
<script>console.log($.request);</script>
</body>
</html>
Option 2
title = "Page 1"
url = "/page-1"
==
<html>
<body>
<h1>PAGE 1</h1>
<a href="/page-2">Open page 2</a>
<script data-turbo-eval="false" src="{{ ['@jquery', '@framework.bundle'] | theme }}"></script>
<script>console.log($.request);</script>
</body>
</html>
Documentation for this scenario added here: octobercms/docs@f019b8c