rstacruz / sinatra-assetpack

Package your assets transparently in Sinatra.
http://ricostacruz.com/sinatra-assetpack/
MIT License
542 stars 97 forks source link

support for CDN with fallback #166

Closed rolandjitsu closed 9 years ago

rolandjitsu commented 10 years ago

Is it possible to have a fallback for the assets that we link, something similar to:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>

I'm coming from a .NET world and we usually use something called Bundler. For some assets, we need to add a fallback just in case that the CDN is not available, so the above piece of code is generated for us.

Perhaps there is a workaround that we can use, maybe manually use the code pasted above and check if in dev or production and output the right strings ?

Update I've just tried this:

js :angular, '/vendor/angular.js', ['/vendor/angular/angular.js']
script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"
javascript:
  window.angular || document.write(#{ js :angular });

But the result is not what I expect.

<script type="text/javascript">window.angular || document.write("<script src='/vendor/angular/angular.38d4d97eb9577f57383d515552f84e1f.js'></script>"");"

I would expect it to be:

<script type="text/javascript">window.angular || document.write('<script src="/vendor/angular/angular.38d4d97eb9577f57383d515552f84e1f.js"><\/script>');</script>

Any suggestions on how I could do it following this pattern ?

rolandjitsu commented 9 years ago

I've managed to do it another way, though I think it should be part of the gem, it would be a nice addition.

kolb0401 commented 9 years ago

Can you elaborate on how you managed to accomplish this?

rolandjitsu commented 9 years ago

@fumblesandfriends oh, nothing complicated, since I only needed one resource to be available from some CDN, so in my view (slim template) I had:

script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.13/angular.min.js"
javascript:
    window.angular || document.write('#{{ parse_cdn_fallback(js :angular) }}');

And the helper parse_cdn_fallback, because I had some issues if I didn't escape some characters:

def parse_cdn_fallback(script)
    script.gsub('</script>', '<\/script>').gsub(/'/, '"')
end

I sure that something similar could be implemented in this lib, since basically the above is what it should output (in the template), but that of course, might be a bit more complicated that I think it should.