Skip to content

Instantly share code, notes, and snippets.

@cloudify
Created November 14, 2011 18:22
Show Gist options
  • Save cloudify/1364679 to your computer and use it in GitHub Desktop.
Save cloudify/1364679 to your computer and use it in GitHub Desktop.
Coffeescript function that execute some code making sure that jQuery is available (i.e. loading the script if not already included in the page)
# Checks wether jQuery is available, if not it will try to load it
# On success (either jquery already available or successfully loaded), the
# success_cb function gets called with the jQuery object passed as paramenter
# On failure (meaning no jQuery available), the fail_cb is called
withJQuery = (success_cb = (-> true), fail_cb = (-> true), jquery_url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js') ->
# create fake console object if the real console is not enabled
console ||=
log: -> true
debug: -> true
if typeof(jQuery) != 'undefined'
# TODO possibly check for version conflicts
console.debug "jQuery already included by host page, version #{jQuery().jquery}"
success_cb(jQuery)
return
thisPageUsingOtherJSLibrary = true if typeof($) == 'function'
getScript = (url, on_script_load) ->
console.debug "loading jQuery script from #{url}"
script = document.createElement('script')
script.src = url
head = document.getElementsByTagName('head')[0]
done = false;
# Attach handlers for all browsers
script.onload = script.onreadystatechange = ->
if !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')
console.debug 'done loading jQuery script'
done = true
on_script_load()
script.onload = script.onreadystatechange = null
head.removeChild(script)
head.appendChild(script)
getScript jquery_url, ->
if typeof jQuery == 'undefined'
# error during load
fail_cb()
else
# jQuery loaded! Make sure to use .noConflict just in case
jQuery.noConflict() if thisPageUsingOtherJSLibrary
success_cb(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment