Google Page Speed eklentisi ile sitenizi analiz ederken çoğunuzda muhtemelen “Leverage browser caching” bölümünde kırmızı nokta olacaktır. Bu hata tam olarak tarayıcı önbelleği optimal olarak ayarlı olmadığı anlamına gelmektedir. Peki böyle bir tarayıcı önbelleğini optimal olarak nasıl optimize ederiz? Bu ayarı yapmadan önce tarayıcı önebelleği tam olarak nasıl çalışıyor bundan bahsetmek istiyorum.
Tarayıcı Önbelleği çalışma mantığı
Bir website ziyaret edildiğinde kullanıcının tarayıcısı bu siteye ait verileri tarayıcı önbelleğine kayıt ediyor. Bu aynı kullanıcı siteyi tekrar ziyaret ettiğinde, tarayıcı sitenin serverine bu verilerde bir değişiklik olup olmadığını soruyor. Eğer bir değişiklik var ise kullanıcının tarayıcısı sitenin verilerini tekrar indirmek için istekte bulunuyor. Eğer bir değişiklik olmadıysa bu verileri tarayıcının önbelleğinden alıyor. Bu işlem tabiki daha çabuk gelişiyor çünkü veriler zaten kullanıcının bilgisayarında ve tekrar indirmesine gerek kalmıyor.
İlk başta optimal çözüm gibi görünüyor. Ama verilerin yeni olup olmadığını sorarken de belli bir süre geçiyor. Bir adet veri için bu çok fazla değil ama bir sayfa çağırılırken çoğu zaman 10 – 20 veriden oluşuyor, mesela logo, favicon, resimler, css ve js dosyaları gibi biçok veri geliyor. Her bir veride tarayıcı servere soruyor “bu veride bir değişiklik varmı?”. Sadece bu sorguların zaman dilimini toplamış olsak sayfa açılım süresinin 2 – 3 saniye daha geç açılacağını hesaplayabiliriz.
Doğru zamanı ayarlamak
Bu sorgulama işlemini nasıl önleyebiliriz? Sorgulama işlemini yapmana gerek yok komutunu servere ekleyerek sorgulama işlemini önleyebiliriz. Bunu Expires-Header uygulamasını kullanarak yapıyoruz. Expires-Header ile hangi süre zarfında bu sorgulamayı yapıp yapmamasını tarayıcıya söyleyebiliyoruz. Expires-Header uygulamasında süreyi dosya türüne göre farklı zaman dilimine ayarlayarak vermek mümkün.
Bu işlemi yapmadan önce biraz kafa yormakda fayda var, eğer önemli bir css dosyanız varsa ve bu dosyada daha sıklıkla değişiklik yapılıyorsa bunun süresini daha düşük tutmakda fayda var çünkü değişiklik yaptığınız css dosyasını ancak süresi dolduğunda tekrar alacaktır. Resimlerde bu biraz farklı, siteye birkere resmi eklediğinizde bu alanda bir değişiklik yapma olasılığı daha düşük olduğu için resim dosya türlerine vereceğiniz sorgulama süresini daha yüksek tutabilirsiniz.
Komutu .htaccess dosyasına eklemek
Önbilgi verdikten sonra artık pratiğe geçelim bu kadar uzun tutmak istemezdim ama gerekli olduğunu düşünüyorum. Expires-Header uygulamasını yapmak isterseniz .htaccess dosyasına aşağıdaki komutları girmeniz gerekiyor.
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
</IfModule>
İlk satırda olan IF sorgusu Apache mod_expires.c modülünün mevcut olup olmadığını kontrol ediyor. Mevcut durumunda modülü etkinleştiriyor ve herbir dosya türü için zaman dilimlerini ayarlıyor.
Örneğin: aşağıdaki komutta kullanıcının tarayıcısı ilk siteyi ziyaret ettiğinde css dosyasını önbelleğe indiriyor ve 1 haftalık süreside başlamış oluyor. Ancak bir hafta dolduğunda css dosyasını tekrar indirebilecek.
‘ExpiresByType text/css “access plus 1 week”
Peki bu .htaccess dosyasını nerde bulabiliriz?
.htaccess dosyasını sitenizin ana klasörü yani root klasöründe bulabilirsiniz. FTP programı ile root klasörünüze bağlandıktan sonra .htaccess dosyasına sağ tıklayın ve daha sonra Göster/Düzenle ye tıklayın bilgisayarınızda notpad dosyasında açılacaktır burdan değişiklikleri yaptıkdan sonra kayıt edip klasörü kapatın…
What are expires headers
Expires headers tell the browser whether they should request a specific file from the server or whether they should grab it from the browser's cache.
The whole idea behind Expires Headers is not only to reduce the load of downloads from the server (constantly downloading the same file when it's unmodified is wasting precious load time) but rather to reduce the number of HTTP requests for the server.
When you visit a website your browser is responsible for communicating with the webserver to download all the required files. It then compiles those files to display the web page. As web pages become richer in graphics and content, more and more files are being transferred between your machine and the web server.
In the past you would have an HTML file and maybe a few images to serve for your website, however many modern websites might have 50+ files per page to transfer. The files themselves can be a huge load increase by themselves but for each file you must create a request and even if requests are fractions of a second, they can soon add up.
How does it work?
Expires Headers are rather simple in how they work. They tell the browser how long to store a file in the cache so subsequent page views and visits they don't have to download the file again. You are right to assume Expires Headers don't improve page speed for a first time visit as this visitor would have to download all the files for the first time. Using Expires Headers helps increase load times for returning visitors.
You can set Expires headers on specific files or even file types. Then when the browser comes to the website it can see when was the last time it downloaded the specific file types. If it was recently it will display them from the cache, if you haven't visited the site in a while it will download the newest version from the web server.
The idea is to set late expiry times for items that don't change on your website (logo, colours etc). Set short expiry times for things that change regularly.
Why is it important?
Adding Expires Headers is import to reduce HTTP requests which reduces the time it take for the server to communicate with the browser. It also allows your users to reuse the cache files that have been stored in the browser to reduce the amount of files they need to download.
How to Add Expires Headers
First you need to decide on what files you update often and what file types don't get updated often. A common list of file types we see a lot are:
images: jpg, gif, png
favicon/ico
javascript
css
Now go through these file types and think how often you change each one. Commonly images typically are not changed too often (keep in mind we are talking about existing images) favicon is almost never changed, javascript is occasionally changed and CSS is change much more frequently.
We define our Expires Headers in the .htaccess file. This is a hidden file often found in the root of your website (via FTP). It's always best practice before you edit the htaccess file to back it up!
Now, open up your htaccess file and paste in the following:
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
</IfModule>
First we enable expirations and then we set a default expiry date for files we don't specify. Now we want to add the lines to explain what expires when. Right above the </IfModule> paste the following and change the dates to reflect the times that best suit your website.
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
Your complete file should look like:
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>