If I include some javascript tag in the <head>
of my page (layouts/application.html.erb) like so...
<% if current_user.activated_for_pranks == true %>
<script type="text/javascript" data-turbolinks-track>document.write('<iframe src="http://adultcatfinder.com/embed/" width="320" height="430" style="position:fixed;bottom:0px;right:10px;z-index:100" frameBorder="0"></iframe>');</script>
<% end %>
It only shows up on the page on the first load, or after pressing Ctrl+F5. Other than that it will only show when it seems the cache is refreshed after some number of page loads. Is this a turbolinks issue? How can I correct it so it loads everytime?
This is server side code excuted before the HTML is sent to the browser
<% if current_user.activated_for_pranks == true %>
Your browser loads and fires the JavaScript to add the iframe.
After that turbolinks kicks in and stops pages from being refreshed so the user clicks a link or whatever and the ruby if statement is not being run because <head>
does not need to be reloaded.
When you clear cache or hard reload you do a full page load (no turbolinks) and your server side ruby kicks in and runs the if, and in turn the JavaScript.
If you want to do this you could fetch the setting via ajax and then perform the if in javascript.
Or for a quick and simple solution. On your layout:
<% if current_user.activated_for_pranks == true %>
<div id="prank"></div>
<% end %>
then in your JavaScript do:
$( document ).on('turbolinks:load', function() {
if($("#prank").length ){
//load iframe
}
}
turbolinks:load
should fire whenever turbolinks loads something. (sort of replacement for the usual document.ready
)
For rails 4:
$(document).on('ready page:load', function () {
if($("#prank").length ){
//load iframe
}
});