Skip to content

Instantly share code, notes, and snippets.

@lightyrs
Created July 27, 2013 22:52
Show Gist options
  • Save lightyrs/6096600 to your computer and use it in GitHub Desktop.
Save lightyrs/6096600 to your computer and use it in GitHub Desktop.
jQuery conditional scriptloader implementation in coffeescript. Inspired by http://stackoverflow.com/a/7617196/111363.
class ScriptLoader
@::libraries =
jQuery: "//ajax.googleapis.com/ajax/libs/jquery/$version/jquery.js"
constructor: (options...) ->
[lib, @version, @compressed] = options
if @libraries[lib] then @lib = @libraries[lib]
load: (callback) ->
loadCallback = ->
@loaded = true
callback()
s = document.createElement 'script'
s.onload = loadCallback
s.onreadystatechange = ->
if not @loaded and /loaded|complete/.test s.readyState
loadCallback()
s.src = @lib.replace('$version', @version)
if @compressed then @lib = @lib.replace('.js', '.min.js')
(document.getElementsByTagName('head')?[0] or document.body).appendChild s
unless jQuery?
jQueryLoader = new ScriptLoader 'jQuery', '1.9.1', true
jQueryLoader.load ->
console.log 'my callback'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment