简体   繁体   中英

UserReport and Turbolinks - How to make JS turbolinks compatible?

I'm running rails, and I've got this code at end of my body tag.

:javascript
  var _urq = _urq || [];
  _urq.push(['initSite', 'mySiteId']);
  (function() {
  var ur = document.createElement('script'); ur.type = 'text/javascript'; ur.async = true;
  ur.src = ('https:' == document.location.protocol ? 'https://cdn.userreport.com/userreport.js' : 'http://cdn.userreport.com/userreport.js');
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ur, s);
  })();

No matter what I do, clicking any and all turbolink enabled links breaks this code. The button disappears.

I've tried encapsulating the code inside a function called userReport, and then doing something like this:

$(document).ready(userReport);
$(document).on('page:load', userReport);

This does not work.

Suggestions are very welcome :)

Your script at the end of the body section, just inserts script element into html's head section every time the body is reloaded. I wonder, why do you need to do it this way? Because, every time one clicks a link, you'll get a duplicate script element in doc's head section (thanks to turbolink's magic). This may be the reason of your problem.

If you really need to do this by javascript, try to add your code at the end of app/assets/javascript/application.js (it's not recommended, I know, but just to test the idea). Hope it helps.

UPDATE According to UserReport's docs the javascript snippet should belong to the head section. To do it the same way, as it's shown in their example you could place the script inside a 'userreport' partial and use that partial inside app's layout template:

<head>
  …
  <%= render 'layots/userreport' %>
</head>

Unfortunately, the userreport.js script does not enable a "reloading" of the widget, so this is not possible.

I extracted the code from the CDN, modified it and use it in my assets so that i can call reset_user_report(); whenever I want to show the widget, (see this repo : https://github.com/nicolasmlv/userreport-turbolinks )

Use at your own risk because it will not use anymore the userreport cdn (features updates / bug fixing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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