9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
# File 'lib/script_relocator.rb', line 9
def call(env)
status, , response = @app.call(env)
if ['Content-Type'] !~ %r{^text/html}
return status, , response
end
response_body = ''
response.each { |part| response_body << part }
return status, , response unless response_body =~ /\A<!DOCTYPE/
doc = Nokogiri::HTML(response_body)
target = doc.at('body')
scripts = doc.css('script')
return status, , response if scripts.empty?
scripts.each do |s|
next if s['async'] == 'async' || s['defer'] == 'defer'
s['data-turbolinks-eval'] = 'false' if s.parent.name == 'head'
s.remove
target << s
end
transformed_body = doc.to_html(save_with: Nokogiri::XML::Node::SaveOptions::NO_DECLARATION | Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS | Nokogiri::XML::Node::SaveOptions::AS_HTML)
if .key?('Content-Length') &&
['Content-Length'].to_i != transformed_body.length
['Content-Length'] = transformed_body.length.to_s
end
return status, , [transformed_body]
end
|