在发布到AWS S3之前,如何压缩/ gzip我的模拟.js和.css文件?

时间:2015-05-19 03:41:18

标签: css powershell amazon-web-services amazon-s3 gzip

我运行了Google的网页速度,它建议压缩我的.js和.css

在首屏内容中消除渲染阻止JavaScript和CSS 显示如何修复

Enable compression
Compressing resources with gzip or deflate can reduce the number of bytes sent over the network.
Enable compression for the following resources to reduce their transfer size by 210.9KiB (68% reduction).
Compressing http://xx.com/content/bundles/js.min.js could save 157.3KiB (65% reduction).
Compressing http://xx.com/content/bundles/css.min.css could save 35.5KiB (79% reduction).
Compressing http://xx.com/ could save 18.1KiB (79% reduction).

在我发布的过程中,我有一个步骤,它使用Windows Powershell将.js和.css模仿的bundle移动到S3,然后转到cloudfront。

我可以在PowerShell脚本中添加一些可以压缩.js和.css文件的步骤吗?

此外,一旦文件被压缩,那么除了更改名称之外我还要做更多的事情,以便告诉我的浏览器它需要尝试接受gzip文件吗?

3 个答案:

答案 0 :(得分:6)

您可以在上传脚本中添加gzip压缩文件所需的代码。

一些示例代码可能是这样的:

function Gzip-FileSimple
{
    param
    (
        [String]$inFile = $(throw "Gzip-File: No filename specified"),
        [String]$outFile = $($inFile + ".gz"),
        [switch]$delete # Delete the original file
    )

    trap
    {
        Write-Host "Received an exception: $_.  Exiting."
        break
    }

    if (! (Test-Path $inFile))
    {
        "Input file $inFile does not exist."
        exit 1
    }

    Write-Host "Compressing $inFile to $outFile."

    $input = New-Object System.IO.FileStream $inFile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read)

    $buffer = New-Object byte[]($input.Length)
    $byteCount = $input.Read($buffer, 0, $input.Length)

    if ($byteCount -ne $input.Length)
    {
        $input.Close()
        Write-Host "Failure reading $inFile."
        exit 2
    }
    $input.Close()

    $output = New-Object System.IO.FileStream $outFile, ([IO.FileMode]::Create), ([IO.FileAccess]::Write), ([IO.FileShare]::None)
    $gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)

    $gzipStream.Write($buffer, 0, $buffer.Length)
    $gzipStream.Close()

    $output.Close()

    if ($delete)
    {
        Remove-Item $inFile
    }
}

从此网站:Gzip creation in Powershell

答案 1 :(得分:5)

Powershell community extensions有一个用于gzipping文件的scriptlet,它非常易于使用:

Write-Gzip foo.js #will create foo.js.gz
mv foo.js.gz foo.js -Force

您不必重命名文件,只需添加Content-Encoding标题并将其设置为gzip

答案 2 :(得分:0)

由于Amazon S3仅用于提供静态文件,因此它不会压缩文件(资产),这就是您需要自己压缩文件的原因:

  • 使用gzip压缩你的.js和.css:我不知道如何使用PowerShell,但我使用Python,我建议制作一个python部署脚本(更好的是{{3} })并在其上集成压缩和推送代码。

  • "此外,一旦文件被压缩,那么除了更改名称之外我还要做更多的事情,以告诉我的浏览器它需要尝试接受gzip文件吗?" :好问题!没有必要更改压缩文件的名称,我建议不要重命名。但是,你:

  • 必须还设置标题"内容编码:gzip"否则浏览器将不知道该文件。

  • 必须设置标题'内容类型':类型(类型='应用程序/ javascript'或' text / css')

  • 必须设置标题' x-amz-acl':' public-read':以使其可公开访问。

  • 我建议设置标题" Cache-Control:max-age = TIME" (例如:TIME = 31104000,360天):帮助浏览器缓存它(更好的性能)

无论是从源还是使用Cloudfront提供服务,都可以使用。但请记住,如果您使用cloudfront提供服务,则需要在每次推送后使所有文件无效,否则旧版本将在推送后24小时内完成。希望这有帮助,如果需要,我可以提供python解决方案。