0

我有一个基于 jQuery mobile 和 MVC 的移动网站。不幸的是,有一些问题是 javascript 和 CSS 文件缓存在手机上,当我在网上进行一些更新时并不总是重新加载。

现在我正在为我的部署过程搜索一个 powershell 脚本,该脚本借助模式向所有 javascript 和 css 链接添加字符串“ ?v= randomnumber ”,以便每次更新时都会新加载 javascript 和 css 文件。例子:

<script type="text/javascript" src="http://localhost/scripts/myscript.js?v=21876">

当我使用 MVC 时,这个替换应该适用于放置在“views”文件夹及其所有子文件夹中的所有文件。

我不是在寻找缓存问题的其他解决方案。

所以第一步是循环“views”文件夹中的所有文件。我这样做了:

Get-ChildItem -Path "C:\inetpub\wwwroot\Inet\MyApp\Views" | ForEach-Object {

}

感谢您的帮助!

4

1 回答 1

1

要实现这一点,您需要进行某种搜索和替换,以下内容应该可以帮助您,这将使用 guid 作为唯一标识符。

$guid    = [guid]::NewGuid()
$Search  = "myscript.js"
$Replace = "myscript.js?v=$guid"

Get-ChildItem -Path "C:\inetpub\wwwroot\Inet\MyApp\Views" | ForEach-Object {
    get-content $_ | % {$_ -replace $Search,$Replace} | Set-Content $_ -Force
}

不过要提到的一件事是 MVC 4 可以自动执行此操作 -捆绑和缩小

编辑:使用正则表达式的更详细示例

$guid    = [guid]::NewGuid()
$regex  = ".js|.css"
$replace = "?v=$guid"

Get-ChildItem -Path "C:\inetpub\wwwroot\Inet\MyApp\Views" | ForEach-Object {

    # store the filename for later and create a temporary file
    $fileName = $_
    $tempFileName = "$_.tmp" 
    new-item $tempFileName -type file -force | out-null

    get-content $_ | % {

        # try and find a match for the regex
        if ($_ -match $regex)
        {
            # if a match has been found append the guid to the matched search criteria
            $_ -replace $regex, "$($matches[0])$replace" | Add-Content $tempFileName 
        }
        else
        {
            # no match so just add the text to the temporary file
            $_ | Add-Content $tempFileName 
        }
    } 

    # copy the temporary file to the original file (force to overwrite)
    copy-item $tempFileName $fileName -force

    # remove the temp file
    remove-item $tempFileName 
}
于 2013-04-29T08:38:13.927 回答