Skip to content

Instantly share code, notes, and snippets.

@intinig
Created February 18, 2014 14:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intinig/9072053 to your computer and use it in GitHub Desktop.
Save intinig/9072053 to your computer and use it in GitHub Desktop.
@Injector =
init: ->
console.log("Initializing")
@checkAndInjectjQuery()
checkAndInjectjQuery: ->
if jQuery?
console.log("jQuery detected, checking version...")
if @versionCompare(jQuery.fn.jquery, "2.0.3") < 0
console.log("jQuery v#{jQuery.fn.jquery} too old, injecting 2.0.3...")
@injectjQuery(true)
else
console.log("jQuery v#{jQuery.fn.jquery} is fine, using it.")
@jq = window.jQuery
else
console.log("jQuery not found, injecting 2.0.3...")
@injectjQuery(false)
injectjQuery: (saveOriginal) ->
script = document.createElement('script')
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"
head = document.getElementsByTagName('head')[0]
if saveOriginal
@jq = $.noConflict(true)
head.appendChild(script)
@checkLoaded(saveOriginal)
checkLoaded: (saveOriginal) ->
window.setTimeout( =>
if !jQuery?
console.log("jQuery not yet loaded, retrying...")
@checkLoaded(saveOriginal)
else
console.log("jQuery loaded: v#{jQuery.fn.jquery}")
if saveOriginal
temp = @jq
@jq = $.noConflict(true)
window.jQuery = temp
window.$ = jQuery
else
@jq = jQuery
@continueInitialization()
, 500)
continueInitialization: ->
console.log("Do whatever you want in here.")
versionCompare: (v1, v2) ->
v1parts = v1.split('.')
v2parts = v2.split('.')
isValidPart = (x) ->
(/^\d+$/).test(x)
if !v1parts.every(isValidPart) || !v2parts.every(isValidPart)
return NaN
v1parts = v1parts.map(Number)
v2parts = v2parts.map(Number)
l = v1parts.length - 1
for i in [0..l]
if v2parts.length == i
return 1
if v1parts[i] == v2parts[i]
continue
else if v1parts[i] > v2parts[i]
return 1
if v1parts.length != v2parts.length
return -1
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment