Skip to content

Instantly share code, notes, and snippets.

@gunn
Created November 17, 2010 02:45
Show Gist options
  • Save gunn/702900 to your computer and use it in GitHub Desktop.
Save gunn/702900 to your computer and use it in GitHub Desktop.
Helper to load from Google CDN but with fallbacks
def javascript_fallback primary, fallback, test
html = javascript_include_tag( primary )
html << "\n" << content_tag(:script, :type => "text/javascript") do
%Q{
if (#{test}) {
document.write(unescape("%3Cscript src='#{fallback}' type='text/javascript'%3E%3C/script%3E"));
}
}.gsub(/^ {6}/, '')
end
html
end
test "javascript_fallback should work" do
helper_html = javascript_fallback "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js", "/javascripts/jquery-1.4.3.min.js", "typeof jQuery == 'undefined'"
raw_html = %q{
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='/javascripts/jquery-1.4.3.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
}.gsub(/^ {6}/, '').strip
assert_equal(raw_html, helper_html)
end
/ Usage:
= javascript_fallback "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js", "/javascripts/jquery-1.4.3.min.js", "typeof jQuery == 'undefined'"
= javascript_fallback "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js", "/javascripts/jquery-ui-1.8.6.min.js", "!jQuery.ui"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment