Last active
December 10, 2015 07:58
-
-
Save juliocesar/4405111 to your computer and use it in GitHub Desktop.
Rake task for embedding external (but local) scripts and stylesheets in an HTML page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assuming that the original file is named index.template.html, and the file that will | |
# be actually served is index.html | |
task :bundle do | |
require 'nokogiri' | |
root = File.dirname __FILE__ | |
document = Nokogiri::HTML File.read(root + '/index.template.html') | |
# Get all scripts that have a src attribute and embed their contents, | |
# removing the src attribute | |
scripts = document.css 'script[src]' | |
scripts.each do |script| | |
path = root + '/' + script['src'] | |
if File.exists? path | |
puts "Bundling #{script['src']}" | |
script.content = File.read path | |
script.remove_attribute 'src' | |
end | |
end | |
# Get all externally linked local stylesheets and embed their contents, | |
# replacing it with a <style> tag | |
stylesheets = document.css 'link[rel="stylesheet"][href]' | |
stylesheets.each do |stylesheet| | |
path = root + '/' + stylesheet['href'] | |
if File.exists? path | |
puts "Bundling #{stylesheet['href']}" | |
style = Nokogiri::XML::Node.new 'style', document | |
style.content = File.read path | |
stylesheet.before style | |
stylesheet.remove | |
end | |
end | |
# Write the document over index.html | |
index = File.open root+'/index.html', 'w' | |
document.write_to index | |
index.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment