Make Sure You're @importing Files That Exist

November 03, 2008 · 1 min read

I've started grumbling about optimising the number of HTTP requests per page. There are plenty of reasons you might want to do this, but that discussion is for another post. For now, just know that I don't like unnecessary HTTP requests. And I *really* don't like wasted ones -- like when a CSS `@import` directive points at a file that 404s. I got tired of tracking these down manually across several applications, so I threw together this little Ruby script to do the detective work for me: ```ruby #! /usr/bin/env ruby css_root = File.expand_path(`pwd`.strip) css_files = Dir[File.join(css_root, "**", "*.css")] missing_imports = Hash.new([]) css_files.each_with_index do |css_file, index| imports = File.read(css_file).split(/\n|\r/).grep(/\@import url\((.*)\)/) imports.each do |import| desired_path = import.scan(/url\((["'\ ])?(.*)\1\)/).to_a.first.to_a.last desired_root = desired_path[0,1] == "/" ? css_root : File.dirname(css_file) filesystem_path = File.expand_path(File.join(desired_root, desired_path)) if !File.exists?(filesystem_path) missing_imports[css_file] += [{ :path => filesystem_path, :directive => import }] end end end if missing_imports.any? puts "Missing files declared as imports in CSS:\n\n" missing_imports.keys.each do |origin| puts "Origin: #{origin}" missing_imports[origin].each do |import| puts "Missing @import file: #{import[:path]}" puts "Directive: #{import[:directive]}" end puts "" end else puts "No imported files are missing. Well done." end ``` Run it from the directory that serves as your document root -- for Rails apps, that's `RAILS_ROOT/public/`. It'll either spit out a list of broken imports or give you a pat on the back: ``` Missing files declared as imports in CSS: Origin: /Users/craig/projects/1.8/public/stylesheets/.../find_by_service.css Missing @import file: /Users/craig/projects/1.8/public/stylesheets/.../a_to_z.css Directive: @import url('.../a_to_z.css'); ``` To be clear: I'd prefer `@import` directives didn't exist at all. Each one is an extra HTTP request that could have been avoided by combining stylesheets. But they're popular with a lot of people, so I'll compromise: if you must use them, at least make sure they point at files that actually exist.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.