项目中静态文件的访问

wwfgu00ing 2013-06-23 02:57:26
项目中可能会有大量的JS CSS Image文件

如果要将这些单独放在一个文件里 在项目中的页面中该如何引用

想到的一个方法是js.domain.com image.domain.com...
但是怎么在页面中添加呢 直接在页面中添加该域名
<img src="http://js.domain.com/images/***.jpg />"

大家有什么思路没
...全文
361 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
白云任去留 2013-06-27
  • 打赏
  • 举报
回复
图片、js、css用单独的域名作解析,单独设立网站虚拟目录站点。该域名一般以配置文件存储,引用时读取该配置文件并拼接具体文件路径。
joyhen 2013-06-26
  • 打赏
  • 举报
回复
图片用单独的图片服务器,css文件盒js文件都可以放到这个服务器上的。定制好模板,一键生成,哪有那么费力
tcmakebest 2013-06-26
  • 打赏
  • 举报
回复
这种想法很奇葩,图片也要合并可行吗
Banianer 2013-06-26
  • 打赏
  • 举报
回复
引用 7 楼 wwfgu00ing 的回复:
[quote=引用 4 楼 banian_cn 的回复:] css打包思路 css文件请求 <link type="text/css" rel=stylesheet" href="HttpCom.ashx?a=CommonCss&t=text/css&c=1"></link> webconfig <appsettings> <add key="CommonCss" values="~/xx.css,~/aa.css"/> </appsettings>
<%@ WebHandler Language="C#" Class="HttpCom" %>

using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;

public class HttpCom : IHttpHandler {

    private const bool DO_GZIP = true;
    private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(30);
    
    public void ProcessRequest (HttpContext context) {
        
        HttpRequest request = context.Request;
        
        // Read setName, contentType and version. All are required. They are
        // used as cache key
        string setName = request["a"] ?? string.Empty;
        string contentType = request["t"] ?? string.Empty;
        string version = request["c"] ?? string.Empty;

        // Decide if browser supports compressed response
        bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

        // Response is written as UTF8 encoding. If you are using languages like
        // Arabic, you should change this to proper encoding 
        UTF8Encoding encoding = new UTF8Encoding(false);

        // If the set has already been cached, write the response directly from
        // cache. Otherwise generate the response and cache it
        if (!this.WriteFromCache(context, setName, version, isCompressed, contentType))
        {
            using (MemoryStream memoryStream = new MemoryStream(5000))
            {
                // Decide regular stream or GZipStream based on whether the response
                // can be cached or not
                using (Stream writer = isCompressed ?
                    (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) :
                    memoryStream)
                {

                    // Load the files defined in <appSettings> and process each file
                    string setDefinition = 
                        System.Configuration.ConfigurationManager.AppSettings[setName] ?? "";
                    string[] fileNames = setDefinition.Split(new char[] { ',' }, 
                        StringSplitOptions.RemoveEmptyEntries);
                    
                    foreach (string fileName in fileNames)
                    {
                        byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                        writer.Write(fileBytes, 0, fileBytes.Length);
                    }

                    writer.Close();
                }

                // Cache the combined response so that it can be directly written
                // in subsequent calls 
                byte[] responseBytes = memoryStream.ToArray();
                context.Cache.Insert(GetCacheKey(setName, version, isCompressed),
                    responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
                    CACHE_DURATION);

                // Generate the response
                this.WriteBytes(responseBytes, context, isCompressed, contentType);
            }
        }
    }

    private byte[] GetFileBytes(HttpContext context, string virtualPath, Encoding encoding)
    {
        if (virtualPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
        {
            using (WebClient client = new WebClient())
            {
                return client.DownloadData(virtualPath);
            }
        }
        else
        {
            string physicalPath = context.Server.MapPath(virtualPath);
            byte[] bytes = File.ReadAllBytes(physicalPath);
            // TODO: Convert unicode files to specified encoding. For now, assuming
            // files are either ASCII or UTF8
            return bytes;
        }
    }

    private bool WriteFromCache(HttpContext context, string setName, string version, 
        bool isCompressed, string contentType)
    {
        byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[];

        if (null == responseBytes || 0 == responseBytes.Length) return false;

        this.WriteBytes(responseBytes, context, isCompressed, contentType);
        return true;
    }

    private void WriteBytes(byte[] bytes, HttpContext context, 
        bool isCompressed, string contentType)
    {
        HttpResponse response = context.Response;

        response.AppendHeader("Content-Length", bytes.Length.ToString());
        response.ContentType = contentType;
        if (isCompressed)
            response.AppendHeader("Content-Encoding", "gzip");

        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
        context.Response.Cache.SetMaxAge(CACHE_DURATION);
        context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

        response.OutputStream.Write(bytes, 0, bytes.Length);
        response.Flush();
    }

    private bool CanGZip(HttpRequest request)
    {
        string acceptEncoding = request.Headers["Accept-Encoding"];
        if (!string.IsNullOrEmpty(acceptEncoding) &&
             (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
            return true;
        return false;
    }

    private string GetCacheKey(string setName, string version, bool isCompressed)
    {
        return "HttpCom." + setName + "." + version + "." + isCompressed;
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}
对单独的文件请求 打包一次?[/quote] 这个看需求,可以若干个,也可以整体打包。
gg_lihui 2013-06-25
  • 打赏
  • 举报
回复
图片 拼接到一张图后用CSS 中的背景定位。可以节省流量。 CSS样式一样,一起下载后调用即可。
饕餮123 2013-06-25
  • 打赏
  • 举报
回复
引用 11 楼 wwfgu00ing 的回复:
[quote=引用 10 楼 a407121393 的回复:] [quote=引用 8 楼 leexiaochong 的回复:] 把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
+1 这个肯定是要在页面上去死写了[/quote]
引用 10 楼 a407121393 的回复:
[quote=引用 8 楼 leexiaochong 的回复:] 把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
+1 这个肯定是要在页面上去死写了[/quote] 不是最好的解决方案[/quote] <link rel="dns-prefetch" href="//a.tbcdn.cn"> <link rel="dns-prefetch" href="//img01.taobaocdn.com"> <link rel="dns-prefetch" href="//img02.taobaocdn.com"> <link rel="dns-prefetch" href="//img03.taobaocdn.com"> <link rel="dns-prefetch" href="//img04.taobaocdn.com"> <link rel="dns-prefetch" href="//log.mmstat.com"> <link rel="dns-prefetch" href="//pcookie.taobao.com"> <link rel="dns-prefetch" href="//p.tanx.com"> <link rel="dns-prefetch" href="//i.mmcdn.cn"> 淘宝也是这样搞的
喂大的程序员 2013-06-25
  • 打赏
  • 举报
回复
楼主可以去各大行业网站前台扒扒看,UI框架是怎么样引用的, 我是来学习的
wwfgu00ing 2013-06-25
  • 打赏
  • 举报
回复
引用 10 楼 a407121393 的回复:
[quote=引用 8 楼 leexiaochong 的回复:] 把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
+1 这个肯定是要在页面上去死写了[/quote]
引用 10 楼 a407121393 的回复:
[quote=引用 8 楼 leexiaochong 的回复:] 把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
+1 这个肯定是要在页面上去死写了[/quote] 不是最好的解决方案
饕餮123 2013-06-25
  • 打赏
  • 举报
回复
引用 8 楼 leexiaochong 的回复:
把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
+1 这个肯定是要在页面上去死写了
wwfgu00ing 2013-06-25
  • 打赏
  • 举报
回复
引用 8 楼 leexiaochong 的回复:
把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
手动的去写吗
李小冲 2013-06-25
  • 打赏
  • 举报
回复
把js.domain.com css.domain.com image.domain.com都指向到他们所在的网站即可
wwfgu00ing 2013-06-25
  • 打赏
  • 举报
回复
引用 4 楼 banian_cn 的回复:
css打包思路 css文件请求 <link type="text/css" rel=stylesheet" href="HttpCom.ashx?a=CommonCss&t=text/css&c=1"></link> webconfig <appsettings> <add key="CommonCss" values="~/xx.css,~/aa.css"/> </appsettings>
<%@ WebHandler Language="C#" Class="HttpCom" %>

using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;

public class HttpCom : IHttpHandler {

    private const bool DO_GZIP = true;
    private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(30);
    
    public void ProcessRequest (HttpContext context) {
        
        HttpRequest request = context.Request;
        
        // Read setName, contentType and version. All are required. They are
        // used as cache key
        string setName = request["a"] ?? string.Empty;
        string contentType = request["t"] ?? string.Empty;
        string version = request["c"] ?? string.Empty;

        // Decide if browser supports compressed response
        bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

        // Response is written as UTF8 encoding. If you are using languages like
        // Arabic, you should change this to proper encoding 
        UTF8Encoding encoding = new UTF8Encoding(false);

        // If the set has already been cached, write the response directly from
        // cache. Otherwise generate the response and cache it
        if (!this.WriteFromCache(context, setName, version, isCompressed, contentType))
        {
            using (MemoryStream memoryStream = new MemoryStream(5000))
            {
                // Decide regular stream or GZipStream based on whether the response
                // can be cached or not
                using (Stream writer = isCompressed ?
                    (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) :
                    memoryStream)
                {

                    // Load the files defined in <appSettings> and process each file
                    string setDefinition = 
                        System.Configuration.ConfigurationManager.AppSettings[setName] ?? "";
                    string[] fileNames = setDefinition.Split(new char[] { ',' }, 
                        StringSplitOptions.RemoveEmptyEntries);
                    
                    foreach (string fileName in fileNames)
                    {
                        byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                        writer.Write(fileBytes, 0, fileBytes.Length);
                    }

                    writer.Close();
                }

                // Cache the combined response so that it can be directly written
                // in subsequent calls 
                byte[] responseBytes = memoryStream.ToArray();
                context.Cache.Insert(GetCacheKey(setName, version, isCompressed),
                    responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
                    CACHE_DURATION);

                // Generate the response
                this.WriteBytes(responseBytes, context, isCompressed, contentType);
            }
        }
    }

    private byte[] GetFileBytes(HttpContext context, string virtualPath, Encoding encoding)
    {
        if (virtualPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
        {
            using (WebClient client = new WebClient())
            {
                return client.DownloadData(virtualPath);
            }
        }
        else
        {
            string physicalPath = context.Server.MapPath(virtualPath);
            byte[] bytes = File.ReadAllBytes(physicalPath);
            // TODO: Convert unicode files to specified encoding. For now, assuming
            // files are either ASCII or UTF8
            return bytes;
        }
    }

    private bool WriteFromCache(HttpContext context, string setName, string version, 
        bool isCompressed, string contentType)
    {
        byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[];

        if (null == responseBytes || 0 == responseBytes.Length) return false;

        this.WriteBytes(responseBytes, context, isCompressed, contentType);
        return true;
    }

    private void WriteBytes(byte[] bytes, HttpContext context, 
        bool isCompressed, string contentType)
    {
        HttpResponse response = context.Response;

        response.AppendHeader("Content-Length", bytes.Length.ToString());
        response.ContentType = contentType;
        if (isCompressed)
            response.AppendHeader("Content-Encoding", "gzip");

        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
        context.Response.Cache.SetMaxAge(CACHE_DURATION);
        context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

        response.OutputStream.Write(bytes, 0, bytes.Length);
        response.Flush();
    }

    private bool CanGZip(HttpRequest request)
    {
        string acceptEncoding = request.Headers["Accept-Encoding"];
        if (!string.IsNullOrEmpty(acceptEncoding) &&
             (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
            return true;
        return false;
    }

    private string GetCacheKey(string setName, string version, bool isCompressed)
    {
        return "HttpCom." + setName + "." + version + "." + isCompressed;
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}
对单独的文件请求 打包一次?
Banianer 2013-06-23
  • 打赏
  • 举报
回复
js打包同理, image也许得用图片服务器了。或者探讨下更好的image思路
Banianer 2013-06-23
  • 打赏
  • 举报
回复
原理利用gzip压缩打包文件,节省请求和带宽
Banianer 2013-06-23
  • 打赏
  • 举报
回复
css打包思路 css文件请求 <link type="text/css" rel=stylesheet" href="HttpCom.ashx?a=CommonCss&t=text/css&c=1"></link> webconfig <appsettings> <add key="CommonCss" values="~/xx.css,~/aa.css"/> </appsettings>
<%@ WebHandler Language="C#" Class="HttpCom" %>

using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;

public class HttpCom : IHttpHandler {

    private const bool DO_GZIP = true;
    private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(30);
    
    public void ProcessRequest (HttpContext context) {
        
        HttpRequest request = context.Request;
        
        // Read setName, contentType and version. All are required. They are
        // used as cache key
        string setName = request["a"] ?? string.Empty;
        string contentType = request["t"] ?? string.Empty;
        string version = request["c"] ?? string.Empty;

        // Decide if browser supports compressed response
        bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

        // Response is written as UTF8 encoding. If you are using languages like
        // Arabic, you should change this to proper encoding 
        UTF8Encoding encoding = new UTF8Encoding(false);

        // If the set has already been cached, write the response directly from
        // cache. Otherwise generate the response and cache it
        if (!this.WriteFromCache(context, setName, version, isCompressed, contentType))
        {
            using (MemoryStream memoryStream = new MemoryStream(5000))
            {
                // Decide regular stream or GZipStream based on whether the response
                // can be cached or not
                using (Stream writer = isCompressed ?
                    (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) :
                    memoryStream)
                {

                    // Load the files defined in <appSettings> and process each file
                    string setDefinition = 
                        System.Configuration.ConfigurationManager.AppSettings[setName] ?? "";
                    string[] fileNames = setDefinition.Split(new char[] { ',' }, 
                        StringSplitOptions.RemoveEmptyEntries);
                    
                    foreach (string fileName in fileNames)
                    {
                        byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                        writer.Write(fileBytes, 0, fileBytes.Length);
                    }

                    writer.Close();
                }

                // Cache the combined response so that it can be directly written
                // in subsequent calls 
                byte[] responseBytes = memoryStream.ToArray();
                context.Cache.Insert(GetCacheKey(setName, version, isCompressed),
                    responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
                    CACHE_DURATION);

                // Generate the response
                this.WriteBytes(responseBytes, context, isCompressed, contentType);
            }
        }
    }

    private byte[] GetFileBytes(HttpContext context, string virtualPath, Encoding encoding)
    {
        if (virtualPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
        {
            using (WebClient client = new WebClient())
            {
                return client.DownloadData(virtualPath);
            }
        }
        else
        {
            string physicalPath = context.Server.MapPath(virtualPath);
            byte[] bytes = File.ReadAllBytes(physicalPath);
            // TODO: Convert unicode files to specified encoding. For now, assuming
            // files are either ASCII or UTF8
            return bytes;
        }
    }

    private bool WriteFromCache(HttpContext context, string setName, string version, 
        bool isCompressed, string contentType)
    {
        byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[];

        if (null == responseBytes || 0 == responseBytes.Length) return false;

        this.WriteBytes(responseBytes, context, isCompressed, contentType);
        return true;
    }

    private void WriteBytes(byte[] bytes, HttpContext context, 
        bool isCompressed, string contentType)
    {
        HttpResponse response = context.Response;

        response.AppendHeader("Content-Length", bytes.Length.ToString());
        response.ContentType = contentType;
        if (isCompressed)
            response.AppendHeader("Content-Encoding", "gzip");

        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
        context.Response.Cache.SetMaxAge(CACHE_DURATION);
        context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

        response.OutputStream.Write(bytes, 0, bytes.Length);
        response.Flush();
    }

    private bool CanGZip(HttpRequest request)
    {
        string acceptEncoding = request.Headers["Accept-Encoding"];
        if (!string.IsNullOrEmpty(acceptEncoding) &&
             (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
            return true;
        return false;
    }

    private string GetCacheKey(string setName, string version, bool isCompressed)
    {
        return "HttpCom." + setName + "." + version + "." + isCompressed;
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}
吴青峰 2013-06-23
  • 打赏
  • 举报
回复
对,<img src="http://js.domain.com/images/***.jpg />"就类似于图片这样引用。既然你的域名指向不同的站点,那就用域名引用到你相应的文件。基本上大多数网站都类似于这种做法,而且也是比较有效的做法。 我建议,最好有个为文件服务的载体,也就是说,在主项目直接上传到一个专门存储文件、图片、js、css的站点,此站点与你主项目区分开。至于怎么上传,上传大文件还是小文件,你就要琢磨了。如果只是上传一般大小的产品图片,也可以在主程序中引用webservice服务,大文件可以用网络流,一步上传。 这种域名引用的思路,是经过很多人总结出来的,对服务端的分流应该会起到一起作用吧,而且归类也比较清晰,大点的门户项目可以参考这种方式去做。
wwfgu00ing 2013-06-23
  • 打赏
  • 举报
回复
引用 1 楼 banian_cn 的回复:
这个是图片服务器的道理差不多吧。 用配置文件保存文件的网址。 你想把N个文件打包成一个文件?
将所有的JS打包成一个 css打包成一个 image打包成一个
Banianer 2013-06-23
  • 打赏
  • 举报
回复
这个是图片服务器的道理差不多吧。 用配置文件保存文件的网址。 你想把N个文件打包成一个文件?

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧