0

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?

1 Answer 1

1

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
  }
});
Sign up to request clarification or add additional context in comments.

5 Comments

So is it possible for me to run just this snippet of code outside of turbolinks each time?
@daveomcd I have updated answer with a solution of sorts.
thanks! Still trying things to get your code above to work. I even fixed your "ID" typo with prank/prankme, but seems the turbolinks:load isn't firing.. I'll keep you posted with what i get.
If you are on rails 4 I have added an alternative solution. Well spotted on the ID :)
Awesome! happy pranking people!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.