Seph Cordovano
Seph Cordovano

Reputation: 2054

Needing to reload page for javascript to load?

I have a rails app with a notification drop down (similar to facebook or most other social sites) which uses javascript to post the notifications. On most page loads this feature doesn't load until I refresh the page. Any idea why this might be?

I'm not hugely familiar with js to know off-hand so it may be a simple fix.

Upvotes: 0

Views: 61

Answers (1)

Nermin
Nermin

Reputation: 6100

You have Turbolinks enabled I guess. To resolve this problem you have to load your javascript field not only on document ready but also on page fetch. In your .js files add loader for page:load

# will load .js content on document ready
$(function(){
    yourJavascriptFileNameInitialize();
});
# will load content when your route changes using Turbolinks
$(document).on("page:load",function(){
   yourJavascriptFileNameInitialize();
});

function yourJavascriptFileNameInitialize(){
    # put here your code
}

Turbolinks is by default enabled, it uses ajax to fetch new content for the page you load, to reduce content it loads from server (makes your app faster). When this happens you need to again load your .js files because they are loaded but no document ready has been recorded. Thus you have to load also when page:load events happens.

Upvotes: 1

Related Questions