Add version to css file

Auto Version CSS and JS Files

Browsers cache all of the various images, scripts, stylesheets, and other content in order to make subsequent page loads faster. This is a fantastic feature that, when used correctly, can make your website’s user experience much better. But it can also be problematic.

The cache may be set to a ‘timer’ to clear on a certain schedule. But this could leave users seeing incorrect versions next time they visit your website. We need a way to ensure the cache lasts as long as it needs to, and immediately is refreshed when a change is made.

File Naming vs Versioning

File Naming

File naming as a method is the process of changing the file name each time you want to bust the cache. One example of this would be a file naming convention such as «filename_month-day-year.filetype». One will quickly realize that this method is very time consuming to maintain, especially on a website where a particular file (such as a css or js file) is updated frequently. This requires the file itself to be renamed as well as wherever the file is imported at or called from.

Versioning

Versioning as a method is the process of appending a query string including a version number to the file when calling it on the page. Modern browsers have gained this ability that alleviates many of the pains of renaming files or offering the «please clear your cache and perform a hard refresh» solution (if solution is even the correct word for that). Its a fantastic way to ensure the cache can be cleared whenever you want it to, but it seems to remain largely unknown to many web developers I talk to.

Manual Versioning

The first introduction to versioning via query strings I had was a manual process. Manual versioning (increasing the version number manually each time you update the file) is very time consuming and just about as bad as renaming the file each time. The main difference is that the manual update only has to occur wherever you import or call the file rather than renaming the file itself (which proves very problematic in modern frontends using webpack or other compilation forms). That lead me to think, how can this be automated?

Automatic Versioning

Well, it turns out that automatic versioning is very simple and one of those «duh, why didn’t I think of that?» type solutions. I’m not the first person to discover it by any means, but it randomly popped into my mind one day and led me to a series of google searches finding others who had discovered it. So, what is this generic «it» that I keep talking about?

Читайте также:  Отправка формы на AJAX

Let’s think it through for a second. What is unique about a file each time a change is made to it? The «last modified» timestamp! All we have to do is to append the «last modified» timestamp for a file import via a query string. This enables ‘auto versioning’ in the sense that the version will be updated instantly when the file is modified, but remain the same when it isn’t. It’s great, right? The beauty of the abstract idea is that it could be easily applied in any language, framework, or CMS. Let’s look at a few examples of how to do this with PHP, Laravel, and WordPress.

Automatic File Versioning in PHP

 $cssVersion = filemtime('/path/to/file.css'); "> 

Automatic File Versioning in Laravel

Automatic File Versioning in WordPress

 /* * Get timestamps for style.css, app.js */ $style_css_version = filemtime( get_stylesheet_directory().'/style.css' ); define( 'STYLE_CSS_VERSION', $style_css_version ); $app_js_version = filemtime( get_stylesheet_directory() . "/js/app.js" ); define( 'APP_JS_VERSION', $app_js_version ); wp_enqueue_style( 'style', get_bloginfo( 'stylesheet_url' ), array(), STYLE_CSS_VERSION ); wp_enqueue_script( 'custom', get_bloginfo('template_url') ."/js/app.js", array('jquery'), APP_JS_VERSION, true // adds script to footer for non-blocking js load. ); 

One thing to watch out for with some wordpress themes is the ability to remove versioning from script/style enqueues within the functions.php file. If you’re having trouble getting the version to work (or even appear on the frontend source code at all) check for something along the lines of the following code that utilizes wordpress filters to remove versioning.

 function _remove_script_version( $src ) < $parts = explode( '?', $src ); return $parts[0]; >add_filter( 'script_loader_src', '_remove_script_version', 15, 1 ); add_filter( 'style_loader_src', '_remove_script_version', 15, 1 ); 

Источник

Как задавать версии css?

гугл выдаёт много разнообразной информации по поводу того, как задать для css версию и подсовывать самую свежую версию клиенту, не перезагружая её, но вот конкретного примера использования я не нашёл, покажите, пожалуйста, как подобной возможностью пользуетесь вы

Я добавляю версию /style.css?v=2, и меняю ее каждый раз при изменении файла, рандомное число, как советует IceJOKER , ставить наверное все-таки не надо, так как файл перестанет кэшироваться браузером.

Можете использовать Gulp или Grunt сборщики для автоматического добавления версионности для css/js файлов. Также сможете заодно их минимизировать.

Используйте hash в названии файла style.baedb042c16e1bf.css . Для сборки советую использовать webpack.

Делать хеш через вопросительный знак не рекомендуется, могут быть проблемы с кеширующими прокси и CDN.

0leg5ergeev: хеш вычисляется на основании содержимого файла. Поменяли что-то в файле, хеш изменился. Для gulp смотрите gulp-rev.

Я на php получаю timestamp последнего изменения файла. Проблем с производительностью нет, операция достаточно быстрая.
/style.css?ver=1450975943

Преимущества:
— файл берется из кеша до тех пор, пока не был фактически изменен
— нет необходимости помнить какие файлы менял, а какие нет → меньше вероятность ошибки и меньше работы

0leg5ergeev: файл css так и сохраняете style.css, а вот к ссылке уже добавляете случайно число, таким образом браузер в каждый раз будет выдаваться свежая версия css

Читайте также:  Windows define java home

IceJOKER: ну, я хочу как раз чтобы кешилось каждый раз нужное, а тут пролучается, что вообще ничего не кешится. На данный момент в проекте css весит около 100кб, что не очень хорошо

0leg5ergeev: «как задать для css версию и подсовывать самую свежую версию клиенту» — вы противоречите сами себе. если хотите , чтоб кешировался файл, то просто отдавайте его, браузер сам закеширует его. либо в ручную задавайте версию как написал Кирилл

Источник

how to add version of style.css in wordpress

Here is a plugin wordpress.org/plugins/wp-css-version-history that will automatically append a version number in the stylesheet. It creates a new stylesheet which is loaded last. No need to clear cache to see changes. Uses WordPress built in CSS editor and user file lock for team collaboration.

11 Answers 11

Version number is a parameter of wp_enqueue_style() .

As per the Codex, here are all the parameters that wp_enqueue_style accepts.

wp_enqueue_style( $handle, $src, $deps, $ver, $media ); 

So for example to load a stylesheet with a version number you’d do the following:

function wpa_90820() < wp_enqueue_style('my-styles', get_stylesheet_directory_uri() .'/my-styles.css', array(), '1.0' ); >add_action('wp_enqueue_scripts', 'wpa_90820'); 

@Toretto Either you theme is hard-coding it in header.php or your theme is also enqueing it with a different handle (the first parameter). The solution also depends on if you are directly editing your theme’s functions.php or if you’ve created a child theme.

@Toretto, $handle is shown in my response and also described in the link I provided to the Codex page for wp_enqueue_style please do your homework.

@Toretto If your theme is using wp_enqueue_style() to load the stylesheet in question then it’s handle is the first parameter. If your theme is hard-coding the stylesheet in header.php then it won’t have a handle.

If you are a theme developer, you might want to force reload of your assets when you push new version.

So versioning of a theme is done in style.css

/* Theme Name: Your Theme Name Version: 1.0.2 */ 

At the top of your functions.php :

$theme = wp_get_theme(); define('THEME_VERSION', $theme->Version); //gets version written in your style.css 

Later when you enqueue CSS or JS, use THEME_VERSION as fourth argument:

function theme_styles() < wp_enqueue_style('main', get_template_directory_uri().'/css/main.css', [], THEME_VERSION, 'all'); >add_action('wp_enqueue_scripts', 'theme_styles'); 
. /your-theme-name/css/main.css?ver=1.0.2 

Gets handy when you have more assets to care about and don’t want to change them manually.

I used this method for a child theme, so we used get_stylesheet_directory_uri() insted of get_template_directory_uri()

Instead of hardwiring the version, you might find it better in some instances to dynamically version your stylesheet so whenever you change it, it automatically changes and refreshes the browser cache immediately without having to edit your functions.php over and over again.

You can use filemtime() to do that. Here is how to do that in a child-style that references the parent_style

 wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), filemtime( get_stylesheet_directory() . '/style.css' ) ); 

Over time, I’ve come to prefer theme versions, but it’s a great idea to use filemtime() here, if one doesn’t have a consistent theme versioning practice.

Читайте также:  Java enum tostring vs name

This is a great solution! I just used array() for the third parameter because I’m using a custom theme with no parent and it worked perfectly.

Источник

Versioning CSS files to invalidate browser cache

Posted on Mar 01, 2022

When you visit a website for the first time, the browser usually caches the website’s assets (CSS, JavaScript, and image files) on your computer.

Caching is the process of saving a copy of a website’s page. This is done so that the next time you visit (or refresh) the page, some assets can be loaded from the computer.

The benefit of caching is that your computer will perform less requests to the website’s server, reducing internet bandwidth usage for both you and the server.

But the downside of caching is that when you change or update your website’s CSS, JavaScript, or image files, then those changes might not be immediately visible on your website.

This is because the browser serves the CSS file cached on the local computer instead of requesting a new copy from the server.

CSS versioning is a trick used to make the browser notice the change on your CSS file and request a new CSS file instead of serving one from the cache.

To use CSS versioning, you simply need to add a query string parameter on the href attribute in your HTML page.

Consider the example below:

 The query string parameter ?v=2 after the style.css file name is the CSS versioning trick.

Because of the query string parameter, the browser will think you are requesting a new file that has a different name than the cached one.

The one cached is style.css , but the one requested is style.css?v=2 .

And that’s how you can avoid CSS caching with versioning.

The next time you update your CSS file again, you need to bump up the version of your CSS as follows:

By updating the CSS version, any changes you made in the file will be immediately visible on the web page without needing to clear the browser cache first.

Versioning is only needed when you load external CSS files. Internal and inline CSS code is not cached because they are written on the HTML file of the web page that you requested.

I hope this tutorial has been useful for you 🙏

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Оцените статью