Skip to content

Instantly share code, notes, and snippets.

Created December 22, 2012 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4361800 to your computer and use it in GitHub Desktop.
Save anonymous/4361800 to your computer and use it in GitHub Desktop.
Coffeescript version of the JS from this answers on stackoverflow: http://stackoverflow.com/a/2174733/76486 It helps you use jquery in an embedded widget without conflicting with other javascript on the page
main = (window, document, version, callback) ->
[j, d, loaded] = [null, null, false]
if !(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)
script = document.createElement("script");
script.type = "text/javascript";
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
script.onload = script.onreadystatechange = () ->
if !loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")
callback((j = window.jQuery).noConflict(1), loaded = true)
j(script).remove();
document.documentElement.childNodes[0].appendChild(script)
main window, document, "1.7", ($, jquery_loaded) ->
# Widget code here
@barmstrong
Copy link

I can't edit it now (wasn't signed in when creating it) but I ended up changing

document.documentElement.childNodes[0].appendChild(script)

to

(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag)

Because it was throwing errors when inserting into badly formed html (blank line at top of file).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment