Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Preloading background images (Sugarcube 2.0 / Twine 2)

edited January 2017 in Help! with 2.0
Hi! In my current story, the background image shifts with some of the passages. E.g. When you're in a cottage, there's a cottage background, then in a forest there's a forest etc.

I'm looking for a way to preload these images to minimize on players arriving on a black-screen background.

I found this chunk of Javascript code on one of the threads, but it was talking about Harlowe, not SugarCube 2.0. Just checking to see if it's applicable, or I need another solution to the problem. CSS I get, but Javascript does my head in.
(function() {
    var images = [];
    var preload = [ "urlofimage1", "urlofimage2", "urlofimage3" ];
    for (var i = 0; i < preload.length; i++) {
        images[i] = new Image();
        images[i].src = preload[i];
    }
})();

Comments

  • That should work, though I would suggest a variation on that for two reasons.
    1. Some element object constructors are buggy in various browser engines, so document.createElement() should be preferred. That's a general concern about the constructors, I have no specific knowledge that the Image() constructor has issues in any browser engine.
    2. The created images are allowed to go out of scope as soon as the call to the IIFE completes. Meaning that they're free to be garbage collected by the browser, along with the loaded image data.
    My suggestion:
    (function () {
    	var preload = ["urlofimage1", "urlofimage2", "urlofimage3"];
    
    	window._ImageCache = preload.map(function (url) {
    		var image = document.createElement('img');
    		image.src = url;
    		return image;
    	});
    })();
    
  • Awesome! Thank you so much again. Just one more question. Upon reading this, is this creating a function I need to call in the story at specific times, or is this something I need to populate with the urls of my background images in the javascript?
  • The latter. It goes in the Story JavaScript and you populate the preload array with your image URLs. That particular kind of construct is called an IIFE (Immediately Invoked Function Expression).
  • Thanks! I wasn't familiar at all with that expression. Seems I have a whole lot to learn.
  • You aren't the only one.
    DairynGM wrote: »
    Thanks! I wasn't familiar at all with that expression. Seems I have a whole lot to learn.

Sign In or Register to comment.