PERF: stop loading handlebars and ember compilers in prod

(this removes a nice 50K from our initial payload and saves memory)

Also fixes invalid HTML automatically if added to HEAD or /BODY
This commit is contained in:
Sam
2015-11-27 11:58:46 +11:00
parent c8c6034a7a
commit 43d63367fd
9 changed files with 802 additions and 48 deletions

View File

@@ -10,6 +10,10 @@ class SiteCustomization < ActiveRecord::Base
%w(stylesheet mobile_stylesheet embedded_css)
end
def self.html_fields
%w(body_tag head_tag)
end
before_create do
self.enabled ||= false
self.key ||= SecureRandom.uuid
@@ -23,7 +27,32 @@ class SiteCustomization < ActiveRecord::Base
raise e
end
def process_html(html)
doc = Nokogiri::HTML.fragment(html)
doc.css('script[type="text/x-handlebars"]').each do |node|
name = node["name"] || node["data-template-name"] || "broken"
precompiled =
if name =~ /\.raw$/
"Discourse.EmberCompatHandlebars.template(#{Barber::EmberCompatPrecompiler.compile(node.inner_html)})"
else
"Ember.HTMLBars.template(#{Barber::Ember::Precompiler.compile(node.inner_html)})"
end
compiled = <<SCRIPT
Ember.TEMPLATES[#{name.inspect}] = #{precompiled};
SCRIPT
node.replace("<script>#{compiled}</script>")
end
doc.to_s
end
before_save do
SiteCustomization.html_fields.each do |html_attr|
if self.send("#{html_attr}_changed?")
self.send("#{html_attr}_baked=", process_html(self.send(html_attr)))
end
end
SiteCustomization.css_fields.each do |stylesheet_attr|
if self.send("#{stylesheet_attr}_changed?")
begin
@@ -126,7 +155,12 @@ class SiteCustomization < ActiveRecord::Base
val = if styles.present?
styles.map do |style|
lookup = target == :mobile ? "mobile_#{field}" : field
style.send(lookup)
if html_fields.include?(lookup.to_s)
style.ensure_baked!(lookup)
style.send("#{lookup}_baked")
else
style.send(lookup)
end
end.compact.join("\n")
end
@@ -142,6 +176,15 @@ class SiteCustomization < ActiveRecord::Base
@cache.clear
end
def ensure_baked!(field)
unless self.send("#{field}_baked")
if val = self.send(field)
val = process_html(val) rescue ""
self.update_columns("#{field}_baked" => val)
end
end
end
def remove_from_cache!
self.class.remove_from_cache!(self.class.enabled_key)
self.class.remove_from_cache!(key)
@@ -190,6 +233,8 @@ end
# mobile_footer :text
# head_tag :text
# body_tag :text
# head_tag_baked :text
# body_tag_baked :text
# top :text
# mobile_top :text
# embedded_css :text