Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 app... in development environment javascript not firing unless page is refreshed

So I am having an odd issue with my first rails4 app where my page javascript is not firing unless I reload the page.

This is true for both my asset pipeline JS and also inline with content_for JS.

in my /assets/javascripts/cars.js file:

$(function(){
    $("#car_car_make_id").on("change", function(){
        //SET MODELS
        $.ajax({
            url: "/car_makes/" + $(this).val() + "/car_models",
            type: "GET",
            dataType: "json",
            cache: false
        })
        .done(function(data) { model_list(data) })
        .fail(function() { alert("error"); })
    });
});

function model_list(data) {
    $("#car_car_model_id").empty();
    $.each(data, function(i,v){ 
        $("<option />").val(v.id).text(v.name).appendTo("#car_car_model_id");
    });
    //ON COMPLETE SHOW
    $("#car_model_div").show();
}

inline in page with content_for:

<% content_for :head do %>
<script type="text/javascript">
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('yt_vid', {
            height: '390',
            width: '640',
            videoId: '<%= @timeslip.youtube_id %>'
        });
    }
</script>
<% end %>

Both of these only fire if i refresh the page.

For example, if i click a link to the page with the youtube video it will not load. but if I refresh it will. Same with the asset pipeline script, it only makes my ajax call if i reload the page first.

like image 440
Joel Grannas Avatar asked Aug 30 '13 03:08

Joel Grannas


1 Answers

looks like a side effect of the new Turbolinks feature. When you click a link, the page isn't being reloaded -- it's just having its <body> loaded by an AJAX request. So:

In the first case, the $(function{ ... }) isn't being run because document.ready is only fired on the first page load, not reloading the body.

In the second case, the <head> isn't reloaded with turbolinks, just the body. So you're left with the old <script> and it isn't rerun!

Check some of the options for turbolinks, like jquery.tubrolinks.

like image 142
rmosolgo Avatar answered Oct 06 '22 00:10

rmosolgo