 superagent          = require 'superagent'
 
 Styles     = []
+
+CSS_URL_REGEXP = /(url\()([^)]*)(\))/g;
+CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g;
+resolveUrlsInStyle= (style, linkUrl)->
+  doc = style.ownerDocument
+  resolver = doc.createElement("a")
+  style.textContent = resolveUrlsInCssText(style.textContent, linkUrl, resolver)
+  style
+
+resolveUrlsInCssText= (cssText, linkUrl, urlObj)->
+  r = replaceUrls(cssText, urlObj, linkUrl, CSS_URL_REGEXP)
+  r = replaceUrls(r, urlObj, linkUrl, CSS_IMPORT_REGEXP)
+  r
+
+replaceUrls= (text, urlObj, linkUrl, regexp)->
+  text.replace regexp, (m, pre, url, post)->
+    urlPath = url.replace(/["']/g, "")
+    urlPath = new URL(urlPath, linkUrl).href if (linkUrl) 
+    urlObj.href = urlPath
+    urlPath = urlObj.href
+    "#{pre}'#{urlPath}'#{post}"
+
+resolveUrls = (text, href, doc)->
+  resolver = doc.createElement("a")
+  resolveUrlsInCssText(text, href, resolver);
 
 createStyleSheet = (content="", disabled=false)->
   style = document.createElement('style')

  rules = getRules(style.sheet)
  removeStyleSheet(style)
  rules
rulesToText = (prefix, rules)->
  r = _.map rules, (rule)-> prefixRule(prefix, rule);
  r.join(' ');

appendStyle = (entry)->
  rules = getRules(entry.node.sheet)
  if rules
    appendRules(entry, rules) if rules
  else if !!entry.node.href
    href = entry.node.href
    uri = getUriFromHref(href)
    if entry.node.__resource
      # Polyfills go through here.
      rules = textToRules(replaceLinkTagUrls(uri,entry.node.__resource))
      appendRules(entry, rules) if rules
    else
      # Chrome goes here
      # Loading External stylesheets (out of current domain)
      # Only Chrome will use this, since we have tweaked the Polyfill to avoid 2 requests.
      removeStyleSheet(entry.node)
      fetch(href).then (text)->
        rules = textToRules(replaceLinkTagUrls(uri, text))
        appendRules(entry, rules) if rules
        true
addSheet = (prefix, node, doc)->
  entry = findNode(prefix, node)
  unless entry

  new ScopedCss(prefix, null, node).process()

addLink = (prefix, node)->
  addSheet(prefix, node, node.ownerDocument)
  finalize()

removeLink = (node)->
