Skip to content

Instantly share code, notes, and snippets.

@bouze bouze/Preloader.coffee
Last active Nov 22, 2016

Embed
What would you like to do?
WebWorkerでプリロード
@onmessage = (event) ->
# 元スレッドからURLのリストを受け取る
urls = event.data
count = 0
load = (url) ->
xhr = new XMLHttpRequest()
xhr.onreadystatechange = ->
try
if xhr.readyState is 4
count++
if count < urls.length
# 1つ読み込みが終わった通知
postMessage("next")
else
# すべて読み込みが終わった通知
postMessage("end")
catch e
return
xhr.open("GET", url, false)
xhr.send(null)
return
for val in urls then load(val)
return
define ["Preloader"], (Preloader) ->
urls = [
"/assets/images/1.gif"
"/assets/images/2.gif"
"/assets/images/3.gif"
"/assets/images/4.gif"
]
preloader = new Preloader()
preloader.start urls
define ->
class Preloader
# Workerで実行する処理が書かれた外部ファイル
WORKER_CORE_JS: "load.js"
count: 0
constructor: ->
# ブラウザにWebWorkerが実装されてるかチェック
@enableWorker = !!window.Worker
return
start: (urls) =>
@urls = urls
@total = @urls.length
if @total isnt 0
if @enableWorker
# Workerが使えたらWorkerにロードの処理を投げる
@loadWithWorker(@urls)
else
# Workerが使えなかったら今のスレッドでロードする
for val in @urls then @loadWithXHR(val)
return
loadWithWorker: (urls) =>
@worker = new Worker(@WORKER_CORE_JS)
# Workerから受信する関数を設定
@worker.onmessage = @workerHandler
# WorkerにURLのリストを送りつつ実行
@worker.postMessage(@urls)
return
# Worker内でファイルが読み込まれるごとに呼び出されるコールバック関数
workerHandler: (e) =>
switch e.data
when "end"
# Workerを停止
@worker.terminate()
@loadComplete()
when "next"
@loadComplete()
return
loadWithXHR: (url) =>
@xhr = new XMLHttpRequest()
@xhr.open("GET", url, false)
@xhr.onreadystatechange = (data) =>
if @xhr.readyState is 4 then @loadComplete()
@xhr.send(null)
return
loadComplete: =>
@count++
if @count >= @total then console.log "全部読み込み終わった"
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.