Revision of Twine: preloading images from Sun, 02/17/2013 - 02:30

If you use a lot of images in your Twine game, it would be very good of you if you preloaded them at the start of the game - having to wait for images to load during a story, even momentarily, can be distracting.

Now you could bother to [url="http://www.glorioustrainwrecks.com/node/4329"]convert them all to inline Base64[/url], but there's other, less intrusive ways. You could, rather, put every image in your story in invisible img tags in the Start passage:

<html>
<img src="  [url of an image ] " style="display:none;" >
...
</html>

...but of course, that requires you to manually list every image yourself. Here is my recommendation: use this JavaScript that will do it automatically, when the story starts. Just put this in a passage tagged with "script".

(function(){var r="";var s=Wikifier.formatters;for(var j=0;j<s.length;j++){if(s[j].name=="image"){r=s[j].lookahead;
break;}}var div=$("storeArea").firstChild.nextSibling;while(div){if(r){k(new RegExp(r,"mg"),4);
}var b=String.fromCharCode(92);var u=b+"s*['"+'"]?([^"'+"']+(jpe?g|a?png|gif|bmp))['"+'"]?'+b+"s*";
k(new RegExp("url"+b+"("+u+b+")","mig"),1);k(new RegExp("src"+b+"s*="+u,"mig"),1);
div=div.nextSibling;}function k(c,e){do{d=c.exec(div.innerHTML);if(d){var i=new Image();
i.src=d[e];}}while(d);}}());

Update 17/2/13: This now works with images in HTML tags as well.

Update 12/2/13: This will now also preload images used in CSS url( ... ) values. It will search for such values in every passage, include the stylesheet passages, script passages, and inline JavaScript.

Version history:

  1. 17/2/13 - Now works for image files specified in HTML src="..." attributes.
  2. 13/2/13 - CSS preloading now only loads JPEG, JPG, PNG, APNG, GIF and BMP files (that is to say, not font files).
  3. 12/2/13 - Now preloads images specified by CSS URL values too.
  4. 19/1/13 - Initial.

pensive-mosquitoes