Skip to content

Instantly share code, notes, and snippets.

@stephancom
Last active February 21, 2016 11:52
Show Gist options
  • Save stephancom/37a63aaae81da5c8fa0f to your computer and use it in GitHub Desktop.
Save stephancom/37a63aaae81da5c8fa0f to your computer and use it in GitHub Desktop.
unobtrusive coffee script preloader
# by: _ _
# __| |_ ___ _ __| |_ __ _ _ _ __ ___ _ __
# (_-< _/ -_) '_ \ ' \/ _` | ' \ _/ _/ _ \ ' \
# /__/\__\___| .__/_||_\__,_|_||_(_)__\___/_|_|_|
# |_| stephan@stephan.com
# unobtrusive preloader
# applies to all elements with data-preload
# expects
# data-preload: array of image
# data-order: loading order
$ ->
# preload a series of images from filenames returning Image objects
loadSeries = (filenames) ->
_.map filenames, (filename) ->
# console.log "load #{filename}"
i = new Image()
i.src = filename
i
# preload a series of images and attach them to a DOM element
loadAndPrepend = (filenames, destination) ->
_.each loadSeries(filenames), (image) ->
$(destination).append(image)
# $(image).hide()
$('[data-preload]').hide()
.sort (a, b) ->
a.dataset.order > b.dataset.order
.each (i, el) ->
files = $(el).data('preload')
# clear preload to make the DOM easier to read in the debugger
# really not important, can be removed
$(el).attr('data-preload', '[]')
loadAndPrepend(files, el)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment