Stopping cookies being set from a domain (aka “cookieless domain”) to increase site performance

后端 未结 4 692
暗喜
暗喜 2020-12-13 02:52

I was reading in Google\'s documentation about improving site speed. One of their recommendations is serving static content (images, css, js, etc.) from a \"cookieless domai

4条回答
  •  醉话见心
    2020-12-13 03:30

    This is how I've done in my website:

    1. Setup a website on IIS with an ASP.NET application pool
    2. Set the binding host to your.domain.com
      • Note: you cannot use domain.com or else the sub-domain will not be cookieless
    3. Create a folder on the website called Static
    4. Setup another website, point it to Static folder created earlier.
    5. Set the binding host to static.domain.com
    6. Use an application pool with unmanaged code
    7. On the settings open Session State and check Not enabled.

    Now you have a static website. To setup open the web.config file under Static folder and replace with this one:

    
    
      
        
        
        
          
            
          
        
      
      
        
          
        
        
          
            
          
        
      
    
    

    This is going to cache the files for 30 days, remove a RoleManager (I don't know if it changes anything but I removed all I could find), and remove an item from Response Headers.

    But here is a problem, your content will be cached even when a new version is deployed, so to avoid this I made an helper method for MVC. Basically you have to append some QueryString that will change every time you change these files.

    default.css?v=1   ?v=2  ...
    

    My MVC method gets the last write date and appends on the file url:

    public static string GetContent(this UrlHelper url, string link)
    {
        link = link.ToLower();
    
        // last write date ticks to hex
        var cacheBreaker = Convert.ToString(File.GetLastWriteTimeUtc(url.RequestContext.HttpContext.Request.MapPath(link)).Ticks, 16);
    
        // static folder is in the website folders, but instead of
        // www.domain.com/static/default.css I convert to
        // static.domain.com/default.css
        if (link.StartsWith("~/static", StringComparison.InvariantCultureIgnoreCase))
        {
            var host = url.RequestContext.HttpContext.Request.Url.Host;
            host = String.Format("static.{0}", host.Substring(host.IndexOf('.') + 1));
    
            link = String.Format("http://{0}/{1}", host, link.Substring(9));
    
            // returns the file URL in static domain
            return String.Format("{0}?v={1}", link, cacheBreaker);
        }
    
        // returns file url in normal domain
        return String.Format("{0}?v={1}", url.Content(link), cacheBreaker);
    }
    

    And to use it (MVC3 Razor):

    
    

    If you are using another kind of application you can do the same, make a method that to append HtmlLink on the page.

提交回复
热议问题