简体   繁体   中英

Rails 4 headaches with loading/preloading JavaScript games in specific pages

I'm hosting games relying on HTML/CSS/JS on a Rails server. These games are displayed in their own specific view.

vardarac.us

While the asset pipeline loads all game code no matter where you visit in the server (which I'm fine with), the games are only supposed to display in a specific div in a specific view. The resources, like sounds and images to be delivered from my CDN, are only preloaded once the page containing this div is visited.

<div id="game-goes-here"></div>

My current implementation uses preloading scripts for each game. These each contain an event listener attached to $(document).on("page:change", somePreloadingFunction) , along with a window.page variable, to try and ensure that the game code interacts with the user only when that specific div is on the page. The scheme is something like this.

In the view containing a game:

<%= javascript_tag do %>
  window.page = "<%= @game && @game.name %>"
<% end %>

The preloading/UI-setting script:

var ready = function() {
  if(window.page == "specific_game_name") {
    game.gameContainer = $("#game-goes-here"); // Attach UI to this div
    //Load game assets, once loaded begin game display
  }
};
$(document).on("page:change", ready);

This works fine the first time I click a link going to one of my games. But if I then use the back button and try again, I get a blank page or the preloader goes into a never-ending loop and the game is not displayed. The problem is resolved through directly visiting the URL or refreshing anywhere on my site and trying again.

I honestly don't know what might be going wrong here. Is this an issue with Turbolinks or browser caching, both, or something I'm not aware of?

I'd suggest that you first try disabling turbolinks (add "data-no-turbolinks" to the BODY tag) and see if it works. If it does, you're now sure that it is really turbolinks that breaks things. Your first option is to just leave it this way :) If, on the other hand, you want your turbolinks back, I vaguely remember I had to implement both jQuery's standard document ready "handler" AND turbolinks' page:load to make everything work (some months ago when I faced a similar problem), because sometimes the former gets called, and sometimes the latter.

Sorry for not being able to be more specific, but I just can't find that code right now. Anyway, Good luck!

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