asp.net-mvc
In asp.net-mvc you can try this SOen response p>
public static class JavascriptExtension
{
public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename)
{
string version = GetVersion(helper, filename);
return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
}
private static string GetVersion(this HtmlHelper helper, string filename)
{
var context = helper.ViewContext.RequestContext.HttpContext;
if (context.Cache[filename] == null)
{
var physicalPath = context.Server.MapPath(filename);
var version = $"?v={new System.IO.FileInfo(physicalPath).LastWriteTime.ToString("MMddHHmmss")}";
context.Cache.Add(filename, version, null,
DateTime.Now.AddMinutes(5), TimeSpan.Zero,
CacheItemPriority.Normal, null);
return version;
}
else
{
return context.Cache[filename] as string;
}
}
}
And in the View call like this:
@Html.IncludeVersionedJs("/meuscriptminificado.js")
What will result in this:
<script type='text/javascript' src='/meuscriptminificado.js?20111129120000'></script>
ASP.NET Core MVC
In asp.net core (asp.net-mvc 6) there is asp-append-version
and you can use it like this:
<script src="scripts/meujs.js" asp-append-version="true"></script>
<link href="styles/meucss.css" rel="stylesheet" asp-append-version="true" />
PHP
With PHP you can use filemtime
, something that would look like:
<link rel="stylesheet" href="styles/meucss.css?v=<?php echo filemtime('caminho/real/styles/meucss.css'); ?>">
<script src="scripts/meujs.js?v=<?php echo filemtime('caminho/real/scripts/meujs.js'); ?>"></script>
However create a function that can facilitate a lot and in this case just call IncludeVersioned
, like this:
<?php
function IncludeVersioned($file) {
$absoluto = 'ect/var/www/caminho/dos/resources/'; # ajuste aqui
if (is_file($absoluto . $file)) {
$time = $absoluto . $file;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
switch ($ext) {
case 'js':
echo '<script src="', $file,'?v=', $time,'"></script>';
break;
case 'css':
echo '<link href="', $file,'?v=', $time,'" rel="stylesheet">;
break;
default:
echo '<!-- tipo invalido de resource -->';
}
} else {
echo '<!-- resource não encontrado -->';
}
}
?>
<?php IncludeVersioned('scripts/foo.js'); ?>
<?php IncludeVersioned('styles/foo.css'); ?>