Skip to content

Instantly share code, notes, and snippets.

@tmedwards
Created January 8, 2023 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmedwards/d8fa1766edbd936f11959075ac964f67 to your computer and use it in GitHub Desktop.
Save tmedwards/d8fa1766edbd936f11959075ac964f67 to your computer and use it in GitHub Desktop.
Image preload function & macro
/*
Image preload function & macro.
*/
/*
preload(imageURLs)
*/
var preload = (function () {
var loadImage = (function () {
// Image loading attributes.
var imgLoadAttrs = Object.freeze({
decoding : 'sync',
fetchpriority : 'high', // experimental
loading : 'eager'
});
// Whether `<HTMLImageElement>.decode()` is available.
var hasDecode = (function () {
try {
return typeof document.createElement('img').decode === 'function';
}
catch (ex) { /* no-op */ }
return false;
})();
// Return a DOM event-based version if `.decode()` is unavailable.
if (!hasDecode) {
return function (url) {
return new Promise(function (resolve, reject) {
var img = document.createElement('img');
jQuery(img)
.attr(imgLoadAttrs)
.on('abort error load', ev => {
jQuery(img).off();
if (ev.type === 'load') {
resolve(img);
}
else {
var mesg = ev.type + ' loading "' + url + '"';
console.warn(mesg);
reject(new Error(mesg));
}
})
.prop('src', url);
});
};
}
// Elsewise, return the `.decode()` version.
return function (url) {
return new Promise(function (resolve, reject) {
var img = document.createElement('img');
jQuery(img)
.attr(imgLoadAttrs)
.prop('src', url);
img.decode().then(
function () {
resolve(img);
},
function (ex) {
console.warn(ex.message);
reject(ex);
}
);
});
};
})();
function preload(/* variadic */) {
var urls = Array.from(arguments).flat(Infinity);
if (urls.length === 0) {
throw new Error('no URLs specified');
}
return Promise.allSettled(urls.map(loadImage))
.then(function (results) {
return results
.filter(function (result) {
return result.status === 'fulfilled';
})
.map(function (result) {
return result.value;
});
});
}
return preload;
})();
/*
<<preload imageURLs...>>
*/
(function () {
function isNotString(url) {
return typeof url !== 'string';
}
Macro.add('preload', {
handler : function () {
if (State.turns === 0 && !setup.preload.force) {
return this.error('Attempting to preload images outside of `StoryInit` or similar can cause performance and/or readiness issues. Set `setup.preload.force` to `true` if you want to do it anyway.');
}
var urls = this.args.flat(Infinity);
if (urls.length === 0) {
return this.error('no URLs specified');
}
if (urls.some(isNotString)) {
return this.error('URLs must be strings');
}
var lockId = LoadScreen.lock();
preload(urls).then(function () {
LoadScreen.unlock(lockId);
});
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment