简体   繁体   English

Turbolinks:body标签内的javascript代码未按应执行

[英]Turbolinks: javascript codes inside body tag are not executed as they should

I am trying to add Turbolinks power to my website but I am currently facing a problem. 我正在尝试为我的网站添加Turbolinks功能,但是我目前遇到了问题。 I have script tags that used to be in the head section which was executed on page load of specific pages. 我有script标记,该标记曾经位于在特定页面的页面加载时执行的head These scripts should be executed once and on their specific page only. 这些脚本应仅在其特定页面上执行一次。 When I tried Turbolinks, these scripts were not executed at all unless they exist in the initial page (the first page loaded from the server). 当我尝试使用Turbolinks时,这些脚本根本不会执行,除非它们存在于初始页(从服务器加载的第一页)中。 So I moved the scripts to the end of the body section of my HTML page. 因此,我将脚本移到了HTML页面的body部分的末尾。 Here are my findings: 这是我的发现:

1- Normal script tags: 1-普通script标签:
This resulted in executing the code multiple times. 这导致多次执行代码。 So if I load the page once it will execute correctly, if I navigate away from the page and then come back to it, the code will execute twice. 因此,如果我一旦加载该页面即可正确执行,如果我离开该页面导航然后返回页面,则代码将执行两次。 If I do that again then it will execute 3 times ... etc. The code is being executed from sources that starts with VM and ends with 5 digits, example VM29823 that are created in chrome each time it visits a page with script tag inside of its body . 如果我再次执行此操作,它将执行3次...等等。代码是从以VM开头并以5位数字结尾的源中执行的,例如,每次访问带有script标签的页面时,chrome中创建的示例VM29823它的body These scripts are executed even if you are navigating to a different page, for example if I visit page A with script SA then SA will be executed onload of other pages B and C. Which is, of course, not desirable. 即使您导航到另一个页面,这些脚本也会执行,例如,如果我使用脚本SA访问页面A,则SA将在其他页面B和C加载时执行。这当然是不希望的。

2- script tags with data-turbolinks-eval=false : 2-带有data-turbolinks-eval=false script标签:
In that case the script is only executed only if that script was called from the initial page (The first load of the website), which is a similar behaviour of adding the script to the head section instead of the body. 在这种情况下,仅当从初始页面(网站的第一次加载)调用该script时才执行该脚本,这类似于将脚本添加到头部而不是正文的行为。

I need to execute my scripts only once and to their corresponding pages. 我只需要执行一次脚本,然后执行相应的页面即可。

Please help. 请帮忙。

To fix you page specific script problem, I think you may solve it by adding data-turbolinks-track=true with this code (in your specific_page.html.erb), placed within <head> tag: 为了解决您的网页特定脚本问题,我认为您可以通过在位于<head>标记内的以下代码(在specific_page.html.erb中)添加data-turbolinks-track = true来解决此问题:

<head>
    <%=  javascript_include_tag "path/to/specific_page_js", "data-turbolinks-track" => true %>
    ...
</head>

A small disadvantage of this is that turbolinks will request the page to reload when it see the new <script> in the specific page. 这样做的一个小缺点是,当Turbolink在特定页面中看到新的<script>时,它将请求重新加载页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM