Cách tăng speed website

I. Code tăng speed :
Cách 1:Chào các bạn.

Mình viết bài viết này với mục tiêu chia sẻ code tăng tốc độ load nhằm tối ưu hóa website tốt hơn. Một trong những yếu tố góp phần google index nhanh website của bạn.

Về ý tưởng tăng tốc độ load website, mình xin mô tả là đoạn code này dựa trên yếu tố trình duyệt là chủ yếu. Nội dung website khi đã load 1 lần rồi, thì nó sẽ lưu lại dữ liệu là các tập tin javascript, hình ảnh (gif, png, jpg), css,... Ngoài việc lưu lại các tập tin này, thì nó sẽ còn gia tăng chỉ số expires của các tập tin, giúp nó lưu vào trình duyệt lâu hơn.

Bạn cần tạo 3 tập tin sau:

* .htaccess (với nội dung):


#### Gzip
<IfModule mod_rewrite.c>RewriteCond %{REQUEST_FILENAME} -f
RewriteRule 
^(.*)(js|css)$ redir.php?file=$1$2&type=$[L]
</
IfModule>#### Expires<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">Header set Cache-Control "max-age=31449600, public"</FilesMatch>#### Turn off the ETagsHeader unset ETag
FileETag None
#### CharsetAddDefaultCharset UTF-8



* pre.php (với nội dung):


<?php
$path 
pathinfo($_SERVER['SCRIPT_NAME']);
if (
$path['extension'] == 'css')  {
  
header('Content-type: text/css');
}
if (
$path['extension'] == 'js')  {
  
header('Content-type: application/x-javascript');
}
?>
*redir.php (với nội dung):

<?php# this is the file redir.php, to gzip javascript and css
# set the request file name
$file=str_replace(chr(0x0),"",$_REQUEST['file']);$allowedfiles = array('js','gif','png','jpg','css','txt','swf');
if (!
in_array(str_replace(chr(0x2E),"",substr(chr(0x2E).$file,-3)),$allowedfiles)){ exit ("Hacking attempt!"); }# Set Expires, cache the file on the browseheader("Expires:".gmdate("D, d M Y H:i:s"time()+15360000)."GMT");header("Cache-Control: max-age=315360000");# set the last modified time$mtime filemtime($file);$gmt_mtime gmdate('D, d M Y H:i:s'$mtime) . ' GMT';header("Last-Modified:" $gmt_mtime);# output a mediatype headerswitch ($_REQUEST['type']){
  case 
'css':
    
header("Content-type: text/css");
    break;
  case 
'js' :
    
header("Content-type: text/javascript");
      break;
  default:
    
header("Content-type: text/plain");
}
# echo the file's contentsecho implode(''file($file));
if(
extension_loaded('zlib')){
  
ob_end_flush();
  
# set header the content's length;
  # header("Content-Length: ".ob_get_length()); # (It doesn't work? )
  
ob_end_flush();
}
?>
* file php.ini 
zlib.output_compression on
zlib
.output_compression_level 3
zlib
.output_handler on
auto_prepend_file 
"pre.php"
Trong đoạn php.ini này mình đặt tỷ lệ nén ở mức trung bình là 3, tỷ lệ nén file có giá trị từ 0 đến 9 (9 là mức cao nhất). Đoạn code trên mình viết có tính năng lưu cache và sử dụng module nén là deflate, chứ nó chả đã động tới module zlib cũng là nén luôn nhé các bạn.

Mình phân biệt giữa 2 module zlibmodule deflate cho các bạn nắm rõ:

- module zlib: còn được gọi là PHP's zlib output_compression sẽ chỉ được chạy với lớp PHP handler (các files .php chẳng hạn)
- module deflate: còn được gọi là Apache's mod_deflate có thể chạy với bất kỳ tập tin nào như jpg, css, javascript,...

Mục đích tạo php.ini là nhằm nén các tập tin ở lớp PHP handler (.php) giúp bạn có 1 hệ thống nhanh hơn, khi vừa được nén các file sử lý php, nén luôn các tập tin (jpg, css, javscript,...) khi kết hợp nén với module deflate.

Trong đoạn php.ini trên mình đã đặt mức nén ở level 3, và khi kiểm tra bằng phpinfo() kết quả sẽ như sau:


[​IMG]

PHP handler là cái gì ?
Khi chạy một site PHP, server phải cần thông dịch PHP và tạo ra trang web khi người dùng truy cập vào. Tùy vào từng người dùng, thời gian địa điểm mà webiste có thể được tạo ra khác nhau. Code PHP được phiên dịch dựa vào bộ thư viện PHP như PHP4 và PHP5. PHP handler sẽ điều khiển quá trình những gì load lên từ bộ thư viện PHP.

Đây là mô hình web server của chúng ta hoạt động, mọi thứ sẽ diễn ra thông qua lớp thông dịch là PHP, sau khi thông dịch web server sẽ trả về máy người dùng.

Mục đích của mình là sẽ làm mọi thứ nhanh hơn khi qua lớp thông dịch PHP này, đây cũng là ý tưởng để mình viết bài này đó các bạn.

[​IMG]

P/S: Có một số bạn dùng Wordpress có sẵn các plugin, mình nghĩ nếu phân tích ra thì cũng chỉ nằm vỏn vẹn cho các module zlibmodule deflate thôi. Cái quan trọng là chúng ta hiểu về nó thế nào để còn làm việc, chứ không phải có gì là quất cái đó đâu nhé.

Hãy thử và cảm nhận tốc độ load website của bạn nhé.  
Cách 2:
Add code này dzô .htaccess: 

# compress text, html, javascript, css, xml:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/x-js
AddOutputFilterByType DEFLATE text/ecmascript
AddOutputFilterByType DEFLATE application/ecmascript
AddOutputFilterByType DEFLATE text/vbscript
AddOutputFilterByType DEFLATE text/fluffscript
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/vnd.oasis.opendocument.formula-template
</IfModule>
#### Luu cache tu dong
<ifModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 seconds"
    ExpiresByType text/cache-manifest "access plus 0 seconds"

    # Data
    ExpiresByType text/xml "access plus 0 seconds"
    ExpiresByType application/xml "access plus 0 seconds"
    ExpiresByType application/json "access plus 0 seconds"

    # Feed
    ExpiresByType application/rss+xml "access plus 3600 seconds"
    ExpiresByType application/atom+xml "access plus 3600 seconds"

    # Favicon
    ExpiresByType image/x-icon "access plus 15552000 seconds"

    # Media: images, video, audio
    ExpiresByType image/gif "access plus 15552000 seconds"
    ExpiresByType image/png "access plus 15552000 seconds"
    ExpiresByType image/jpeg "access plus 15552000 seconds"
    ExpiresByType image/jpg "access plus 15552000 seconds"
    ExpiresByType video/ogg "access plus 15552000 seconds"
    ExpiresByType audio/ogg "access plus 15552000 seconds"
    ExpiresByType video/mp4 "access plus 15552000 seconds"
    ExpiresByType video/webm "access plus 15552000 seconds"

    # HTC files  (css3pie)
    ExpiresByType text/x-component "access plus 15552000 seconds"

    # Webfonts
    ExpiresByType application/x-font-ttf "access plus 15552000 seconds"
    ExpiresByType font/opentype "access plus 15552000 seconds"
    ExpiresByType font/woff2 "access plus 15552000 seconds"
    ExpiresByType application/x-font-woff "access plus 15552000 seconds"
    ExpiresByType image/svg+xml "access plus 15552000 seconds"
    ExpiresByType application/vnd.ms-fontobject "access plus 15552000 seconds"

    # CSS and JavaScript
    ExpiresByType text/css "access plus 15552000 seconds"
    ExpiresByType application/javascript "access plus 15552000 seconds"
    ExpiresByType text/javascript "access plus 15552000 seconds"
    ExpiresByType application/javascript "access plus 15552000 seconds"
    ExpiresByType application/x-javascript "access plus 15552000 seconds"

    # Others files
    ExpiresByType application/x-shockwave-flash "access plus 15552000 seconds"
    ExpiresByType application/octet-stream "access plus 15552000 seconds"
</ifModule>
##ket thuc luu cache tu dong

II. CODE XÓA BỎ CHẶN CSS VÀ JS


Khi check PageSpeed Insights chắc hẳn không ít bạn đã gặp phải lỗi này. Vậy cách khắc phục như thế nào mà không cần phải loại bỏ CSS hay Javascript? Hãy theo dõi bài viết sau của  nhé.


Bình thường khi chèn Javascript và CSS chúng ta vẫn thường viết theo cách này

<link href='//abc.css' rel='stylesheet' type='text/css'/>

<script src='//abc.js' type='text/javascript'/>

Nhưng khi check PageSpeed Insights sẽ bị báo lỗi như tiêu đề.


Các bạn hãy sửa theo cú pháp sau

Đối với CSS :

Các bạn hãy chèn CSS theo cú pháp sau

 <script type='text/javascript'>
//<![CDATA[
//CSS Ready
function loadCSS(e, t, n) { "use strict"; 
var i = window.document.createElement("link"); 
var o = t || window.document.getElementsByTagName("script")[0]; 
i.rel = "stylesheet"; i.href = e; i.media = "only x"; 
o.parentNode.insertBefore(i, o); 
setTimeout(function () { i.media = n || "all" }) }
loadCSS("Link CSS 1");loadCSS("Link CSS 2");
//]]>
</script>

 <script type='text/javascript'>
//<![CDATA[
//CSS Ready
function loadCSS(e, t, n) { "use strict"; 
var i = window.document.createElement("link"); 
var o = t || window.document.getElementsByTagName("script")[0]; 
i.rel = "stylesheet"; i.href = e; i.media = "only x"; 
o.parentNode.insertBefore(i, o); 
setTimeout(function () { i.media = n || "all" }) }
loadCSS("http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,600");
loadCSS("https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css");
//]]>
</script>

Đối với Javascript :

1. Tìm đường link của script chặn hiển thị có đuôi .js và copy địa chỉ đó vào trong tab mới bạn sẽ thấy code nội dung trong script đó, ví dụ như

 jQuery(document).ready(function () {
jQuery(“#facebook_right”).hover(function () {
jQuery(this).top(true, alse).animate({
right: 0
}, 500);
}, function () {
jQuery(“#facebook_right”).stop(true, false).animate({
right: -200
}, 500);
});
Và vân vân :))

2. Copy và dán nội dung đoạn code vừa tìm được ở trên vào giữa đoạn code sau

 &lt;script type=&#039;text/javascript&#039;&gt;
//Nội dung code
&lt;/script&gt;

Ta sẽ được đoạn code như sau

 &lt;script type=&#039;text/javascript&#039;&gt;
jQuery(document).ready(function () {
jQuery(“#facebook_right”).hover(function () {
jQuery(this).top(true, alse).animate({
right: 0
}, 500);
}, function () {
jQuery(“#facebook_right”).stop(true, false).animate({
right: -200
}, 500);
});
&lt;/script&gt;

3.Dán đoạn code trên vào trước thẻ </body> (Nếu bị lỗi code thì bạn dán code lại tại ngay vị trí bạn tìm thấy đoạn script ở bước 1)

****Bonus:

Trong template bạn sẻ nhìn thấy đoạn java có dạng như sau: 
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' type='text/javascript'/>
Bạn cần thay đoạn trên bằng đoạn mã dưới đây để khắc phục lỗi chặn hiển thị màn hình.
<script async='async' src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' type='text/javascript'/>

Bây giờ bạn hãy check lại PageSpeed Insights xem có còn bị lỗi trên không nhé.

Thủ thuật trên cũng đồng thời làm web của bạn load nhanh hơn chút ít đấy :)

Nếu có bất kỳ vấn đề khó khăn hay câu hỏi gì, bạn đừng ngần ngại, hãy để lại bình luận ở form bên dưới nhé.

Chúc bạn thành công!

 III. CODE RESPONSIVE MOBILE 
 Them code sau vào header:

  <meta name=viewport content="width=device-width, initial-scale=1">IV. NÉN ẢNH HÀNG LOẠT :

Link download: https://drive.google.com/file/d/0B0b-oVFf8THFMVJLLVdleVZLSG8/view?usp=sharing


Còn tiếp T.T
Bài viết được sử dụng từ nhiều nguồn:
1. http://forum.idichvuseo.com/threads/code-tang-toc-do-load-website.2152/

2. http://iris-tips.blogspot.com/2015/06/loai-bo-javascript-va-css-chan-hien-thi.html
Share on Google Plus

About lamnguyen

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 nhận xét:

Đăng nhận xét