Tối ưu magento cho load nhanh hơn

Thảo luận trong 'Magento optimization' bắt đầu bởi admin, 18 Tháng mười một 2012.

  1. admin

    admin Mai Văn Hải Staff Member

    Về độ nặng của Magento là vấn đề ai cũng thấy, tuy nhiên các yếu tố ảnh hướng tới nó lại rất nhiều:
    1. Thư viện các module chức năng: Phụ thuộc vào từng dự án mà bỏ đi.
    2. Thư viện Javascript: Tùy từng dự án mà thêm, bớt
    3. Hệ thống template: html, css

    Đây là vấn đề lớn cần chú ý và tối ưu nó.

    Bản chất Magento có tính kế thừa, do vậy mọi người tuyệt đối chú ý và chỉ chỉnh sửa các file cần thiết bên theme của mình, các phần không dùng thì hãy bỏ bên BASE nhé.

    Sau đây là các chú ý khác mà bác google.com đích thân chỉ dẫn, tôi xin chép nguyên văn và bạn có thể xem bản gốc tại:
    https://developers.google.com/speed/doc ... load?hl=vi
  2. admin

    admin Mai Văn Hải Staff Member

    Enable compression

    Compressing resources with gzip or deflate can reduce the number of bytes sent over the network.

    Most modern browsers support data compression for HTML, CSS, and JavaScript files. This allows content to be sent over the network in more compact form and can result in a dramatic reduction in download time.

    Many web servers can compress files in gzip format before sending them for download, either by calling a third-party module or using built-in routines. To enable compression, configure your web server to set the Content-Encoding header to gzip format for all compressible resources. You can also use deflate, which uses the same compression algorithms, but it is not widely used, so we recommend gzip. If streaming compression imposes too much load on your server, you can usually configure it to pre-compress files and cache them for future downloading.

    Note that gzipping is only beneficial for larger resources. Due to the overhead and latency of compression and decompression, you should only gzip files above a certain size threshold; we recommend a minimum range between 150 and 1000 bytes. Gzipping files below 150 bytes can actually make them larger.

    Write your web page content to make compression most effective.
    To ensure that your content compresses well, do the following:

    Ensure consistency in HTML and CSS code. To achieve consistency:
    Specify CSS key-value pairs in the same order where possible, i.e. alphabetize them.
    Specify HTML attributes in the same order , i.e. alphabetize them. Put href first for links (since it is most common), then alphabetize the rest. For example, on Google's search results page, when HTML attributes were alphabetized, a 1.5% reduction in the size of the gzipped output resulted.
    Use consistent casing, i.e. use lowercase wherever possible.
    Use consistent quoting for HTML tag attributes, i.e. always single quote, always double quote, or no quoting at all where possible.
    Minify JavaScript and CSS. Minifying JavaScript and CSS can enhance compression both for external JS and CSS files and for HTML pages containing inlined JS code and style blocks.

    Don't use gzip for image or other binary files.
    Image file formats supported by the web, as well as videos, PDFs and other binary formats, are already compressed; using gzip on them won't provide any additional benefit, and can actually make them larger. To compress images, see Optimize images.
    Additional resources

    For more tips on ensuring that your content is downloaded in compressed format, see Use compression to make the web faster.
  3. admin

    admin Mai Văn Hải Staff Member

    Minify CSS

    Compacting CSS code can save many bytes of data and speed up downloading, parsing, and execution time.

    Minifying CSS has the same benefits as those for minifying JS: reducing network latency, enhancing compression, and faster browser loading and execution.

    Several tools are freely available to minify JavaScript, including the YUI Compressor and cssmin.js.

    Tip: When you run Page Speed against a page referencing CSS files, it automatically runs cssmin.js on the files and saves the minified output to a configurable directory.
  4. admin

    admin Mai Văn Hải Staff Member

    Minify HTML

    Compacting HTML code, including any inline JavaScript and CSS contained in it, can save many bytes of data and speed up downloading, parsing, and execution time.

    Minifying HTML has the same benefits as those for minifying CSS and JS: reducing network latency, enhancing compression, and faster browser loading and execution. Moreover, HTML frequently contains inline JS code (in <script> tags) and inline CSS (in <style> tags), so it is useful to minify these as well.

    Tip: When you run Page Speed against a page referencing HTML files, it automatically runs the Page Speed HTML compactor (which will in turn apply JSMin and cssmin.js to any inline JavaScript and CSS) on the files and saves the minified output to a configurable directory.
  5. admin

    admin Mai Văn Hải Staff Member

    Defer loading of JavaScript

    Deferring loading of JavaScript functions that are not called at startup reduces the initial download size, allowing other resources to be downloaded in parallel, and speeding up execution and rendering time.

    Like stylesheets, scripts must be downloaded, parsed, and executed before the browser can begin to render a web page. Again, even if a script is contained in an external file that is cached, processing of all elements below the script is blocked until the browser loads the code from disk and executes it. However, for some browsers, the situation is worse than for stylesheets: while JavaScript is being processed, the browser blocks all other resources from being downloaded. For AJAX-type applications that use many bytes of JavaScript code, this can add considerable latency.

    For many script-intensive applications, the bulk of the JavaScript code handles user-initiated events, such as mouse-clicking and dragging, form entry and submission, hidden elements expansion, and so on. All of these user-triggered events occur after the page is loaded and the onload event is triggered. Therefore, much of the delay in the "critical path" (the time to load the main page at startup) could be avoided by deferring the loading of the JavaScript until it's actually needed. While this "lazy" method of loading doesn't reduce the total JS payload, it can significantly reduce the number of bytes needed to load the initial state of the page, and allows the remaining bytes to be loaded asynchronously in the background.

    To use this technique, you should first identify all of the JavaScript functions that are not actually used by the document before the onload event. For any file containing more than 25 uncalled functions, move all of those functions to a separate, external JS file. This may require some refactoring of your code to work around dependencies between files. (For files containing fewer than 25 uncalled functions, it's not worth the effort of refactoring.)

    Then, you insert a JavaScript event listener in the head of the containing document that forces the external file to be loaded after the onload event. You can do this by any of the usual scripting means, but we recommend a very simple scripted DOM element (to avoid cross-browser and same-domain policy issues). Here's an example (where "deferredfunctions.js" contains the functions to be lazily loaded):

    <script type="text/javascript">
     // Add a script element as a child of the body
     function downloadJSAtOnload() {
     var element = document.createElement("script");
     element.src = "deferredfunctions.js";
     // Check for browser support of event handling capability
     if (window.addEventListener)
     window.addEventListener("load", downloadJSAtOnload, false);
     else if (window.attachEvent)
     window.attachEvent("onload", downloadJSAtOnload);
     else window.onload = downloadJSAtOnload;
  6. admin

    admin Mai Văn Hải Staff Member

    Optimize images

    Properly formatting and compressing images can save many bytes of data.

    Images saved from programs like Fireworks can contain kilobytes of extra comments, and use too many colors, even though a reduction in the color palette may not perceptibly reduce image quality. Improperly optimized images can take up more space than they need to; for users on slow connections, it is especially important to keep image sizes to a minimum.

    You should perform both basic and advanced optimization on all images. Basic optimization includes cropping unnecessary space, reducing color depth to the lowest acceptable level, removing image comments, and saving the image to an appropriate format. You can perform basic optimization with any image editing program, such as GIMP. Advanced optimization involves further (lossless) compression of JPEG and PNG files. You should see a benefit for any image file that can be reduced by 25 bytes or more (less than this will not result in any appreciable performance gain).

    Choose an appropriate image file format.
    The type of an image can have a drastic impact on the file size. Use these guidelines:

    PNGs are almost always superior to GIFs and are usually the best choice. IE 4.0b1+, Mac IE 5.0+, Opera 3.51+ and Netscape 4.04+ as well as all versions of Safari and Firefox fully support PNG, including transparency. IE versions 4 to 6 don't support alpha channel transparency (partial transparency) but they support 256-color-or-less PNGs with 1-bit transparency (the same that is supported for GIFs). IE 7 and 8 support alpha transparent PNGs except when an alpha opacity filter is applied to the element. You can generate or convert suitable PNGs with GIMP by using "Indexed" rather than "RGB" mode. If you must maintain compatibility with 3.x-level browsers, serve an alternate GIF to those browsers.
    Use GIFs for very small or simple graphics (e.g. less than 10x10 pixels, or a color palette of less than 3 colors) and for images which contain animation. If you think an image might compress better as a GIF, try it as a PNG and a GIF and pick the smaller.
    Use JPGs for all photographic-style images.
    Do not use BMPs or TIFFs.

    Use an image compressor.
    Several tools are available that perform further, lossless compression on JPEG and PNG files, with no effect on image quality. For JPEG, we recommend jpegtran or jpegoptim (available on Linux only; run with the --strip-all option). For PNG, we recommend OptiPNG or PNGOUT.

    Tip: When you run Page Speed against a page referencing JPEG and PNG files, it automatically compresses the files and saves the output to a configurable directory.
  7. admin

    admin Mai Văn Hải Staff Member

    Serve scaled images

    Properly sizing images can save many bytes of data.

    Sometimes you may want to display the same image in various sizes, so you will serve a single image resource and use HTML or CSS in the containing page to scale it. For example, you may have a 10 x 10 thumbnail version of a larger 250 x 250 image, and rather than forcing the user to download two separate files, you use markup to resize the thumbnail version. This makes sense if the actual image size matches at least one — the largest — of the instances in the page, in this case 250 x 250 pixels. However, if you serve an image that is larger than the dimensions used in all of the markup instances, you are sending unnecessary bytes over the wire. You should use an image editor to scale images to match the largest size needed in your page, and make sure that you specify those dimensions in the page as well.
  8. admin

    admin Mai Văn Hải Staff Member

    Serve resources from a consistent URL

    It's important to serve a resource from a unique URL, to eliminate duplicate download bytes and additional RTTs.

    Sometimes it's necessary to reference the same resource from multiple places in a page — images are a typical example. Even more likely is that you share the same resources across multiple pages in a site such as .css and .js files. If your pages do need to include the same resource, the resource should always be served from a consistent URL. Ensuring that one resource is always assigned a single URL has a number of benefits. It reduces the overall payload size, as the browser does not need to download additional copies of the same bytes. Also, most browsers will not issue more than one HTTP request for a single URL in one session, whether or not the resource is cacheable, so you also save additional round-trip times. It's especially important to ensure that the same resource is not served from a different hostname, to avoid the performance penalty of additional DNS lookups.

    Note that a relative URL and an absolute URL are consistent if the hostname of the absolute URL matches that of the containing document. For example, if the main page at example.com references resource /images/example.gif and example.com/images/example.gif, the URLs are consistent. However, if that page references /images/example.gif and mysite.example.com/images/example.gif, these URLs are not consistent.

    Serve shared resources from a consistent URL across all pages in a site.
    For resources that are shared across multiple pages, make sure that each reference to the same resource uses an identical URL. If a resource is shared by multiple pages/sites that link to each other, but are hosted on different domains or hostnames, it's better to serve the file from a single hostname than to re-serve it from the hostname of each parent document. In this case, the caching benefits may outweigh the DNS lookup overhead. For example, if both mysite.example.com and yoursite.example.com use the same JS file, and mysite.example.com links to yoursite.example.com (which will require a DNS lookup anyway), it makes sense to just serve the JS file from mysite.example.com. In this way, the file is likely to already be in the browser cache when the user goes to yoursite.example.com.
    Last edited: 8 Tháng một 2017
  9. admin

    admin Mai Văn Hải Staff Member

    Minimize request size

    Keeping cookies and request headers as small as possible ensures that an HTTP request can fit into a single packet.

    Ideally, an HTTP request should not go beyond 1 packet. The most widely used networks limit packets to approximately 1500 bytes, so if you can constrain each request to fewer than 1500 bytes, you can reduce the overhead of the request stream. HTTP request headers include:

    Cookies: For resources that must be sent with cookies, keep the cookie sizes to a bare minimum. To keep the request size within this limit, no one cookie served off any domain should be more than 1000 bytes. We recommend that the average size of cookies served off any domain be less than 400 bytes.
    Browser-set fields: Many of the header fields are automatically set by the user agent, so you have no control over them.
    Requested resource URL (GET and Host fields). URLs with multiple parameters can run into the thousands of bytes. Try to limit URL lengths to a few hundred bytes at most.
    Referrer URL.


    Use server-side storage for most of the cookie payload.
    Store only a unique identifier in the cookie, and key the ID to data stored at the server end. You can use server-side cookies for both session and persistent cookies by specifying the expiry date/time on the cookie.
    Remove unused or duplicated cookie fields.
    The fields set by a cookie at the top-level path of a domain (i.e. /) are inherited by the resources served off all paths below that domain. Therefore, if you are serving different applications on different URL paths, and you have a field that applies globally to all applications on a domain — for example, a user's language preference — include that field in the cookie set at the top-level domain; don't duplicate the field in cookies set for subpaths. Conversely, if a field only applies to an application served from a subpath — for example, a UI setting — don't include that field in the top-level cookie and force the unused data to be passed needlessly for other applications.
  10. admin

    admin Mai Văn Hải Staff Member

    Serve static content from a cookieless domain

    Serving static resources from a cookieless domain reduces the total size of requests made for a page.

    Static content, such as images, JS and CSS files, don't need to be accompanied by cookies, as there is no user interaction with these resources. You can decrease request latency by serving static resources from a domain that doesn't serve cookies. This technique is especially useful for pages referencing large volumes of rarely cached static content, such as frequently changing image thumbnails, or infrequently accessed image archives. We recommend this technique for any page that serves more than 5 static resources. (For pages that serve fewer resources than this, it's not worth the cost of setting up an extra domain.)

    To reserve a cookieless domain for serving static content, register a new domain name and configure your DNS database with a CNAME record that points the new domain to your existing domain A record. Configure your web server to serve static resources from the new domain, and do not allow any cookies to be set anywhere on this domain. In your web pages, reference the domain name in the URLs for the static resources.

    If you host your static files using a CDN, your CDN may support serving these resources from another domain. Contact your CDN to find out.

    Enable proxy caching.
    For resources that rarely change, set caching headers for browsers and proxies. Because cookies will not be sent for these resources, there is no risk that proxy caches will cache user-specific content.
    Don't serve early loaded external JS files from the cookieless domain.
    For JavaScript referenced in the head of the document and needed for page startup, it should be served from the same hostname as the main document. Because most browsers block other downloads and rendering until all JavaScript files have been downloaded, parsed and executed, it's better to avoid the risk of an additional DNS lookup at this point of processing.


    Many Google properties, including News and Code (this site), serve static resources, such as JS files and images, from a separate domain. No cookies can be set on this domain. For the News homepage at news.google.com, you can see the cookie in the request header in this screen shot:
    But for www.gstatic.com, which is used to serve the News logo .gif file, no cookie headers appear in the request or response:
    Last edited: 8 Tháng một 2017
  11. admin

    admin Mai Văn Hải Staff Member

    Use efficient CSS selectors

    Avoiding inefficient key selectors that match large numbers of elements can speed up page rendering.

    As the browser parses HTML, it constructs an internal document tree representing all the elements to be displayed. It then matches elements to styles specified in various stylesheets, according to the standard CSS cascade, inheritance, and ordering rules. In Mozilla's implementation (and probably others as well), for each element, the CSS engine searches through style rules to find a match. The engine evaluates each rule from right to left, starting from the rightmost selector (called the "key") and moving through each selector until it finds a match or discards the rule. (The "selector" is the document element to which the rule should apply.)

    According to this system, the fewer rules the engine has to evaluate the better. So, of course, removing unused CSS is an important step in improving rendering performance. After that, for pages that contain large numbers of elements and/or large numbers of CSS rules, optimizing the definitions of the rules themselves can enhance performance as well. The key to optimizing rules lies in defining rules that are as specific as possible and that avoid unnecessary redundancy, to allow the style engine to quickly find matches without spending time evaluating rules that don't apply.

    The following categories of rules are considered to be inefficient:

    Rules with descendant selectors
    For example:

    Rules with the universal selector as the key

            body * {...}
            .hide-scrollbars * {...}
    Rules with a tag selector as the key
            ul li a {...}
            #footer h3 {...}
            * html #atticPromo ul li a {...]
    Descendant selectors are inefficient because, for each element that matches the key, the browser must also traverse up the DOM tree, evaluating every ancestor element until it finds a match or reaches the root element. The less specific the key, the greater the number of nodes that need to be evaluated.
    Rules with child or adjacent selectors
    For example:

    Rules with the universal selector as the key
            body > * {...}
            .hide-scrollbars > * {...}
    Rules with a tag selector as the key

            ul > li > a {...}
            #footer > h3 {...}
    Child and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.
    Rules with overly qualified selectors
    For example:

        ul#top_blue_nav {...}
        form#UserLogin {...}
    ID selectors are unique by definition. Including tag or class qualifiers just adds redundant information that needs to be evaluated needlessly.
    Rules that apply the :hover pseudo-selector to non-link elements
    For example:

        h3:hover {...}
        .foo:hover {...}
        #foo:hover {...}
        div.faa :hover {...}
    The :hover pseudo-selector on non-anchor elements is known to make IE7 and IE8 slow in some cases*. When a strict doctype is not used, IE7 and IE8 will ignore :hover on any element other than anchors. When a strict doctype is used, :hover on non-anchors may cause performance degradation.

    * See a bug report at http://connect.microsoft.com/IE/feedbac ... kID=391387.


    Avoid a universal key selector.
    Allow elements to inherit from ancestors, or use a class to apply a style to multiple elements.
    Make your rules as specific as possible.
    Prefer class and ID selectors over tag selectors.
    Remove redundant qualifiers.
    These qualifiers are redundant:

    ID selectors qualified by class and/or tag selectors
    Class selectors qualified by tag selectors (when a class is only used for one tag, which is a good design practice anyway).

    Avoid using descendant selectors, especially those that specify redundant ancestors.
    For example, the rule body ul li a {...} specifies a redundant body selector, since all elements are descendants of the body tag.
    Use class selectors instead of descendant selectors.
    For example, if you need two different styles for an ordered list item and an ordered list item, instead of using two rules:

        ul li {color: blue;}
        ol li {color: red;}
    You could encode the styles into two class names and use those in your rules; e.g:
        .unordered-list-item {color: blue;}
        .ordered-list-item {color: red;}
    If you must use descendant selectors, prefer child selectors, which at least only require evaluation of one additional node, not all the intermediate nodes up to an ancestor.
    Avoid the :hover pseudo-selector for non-link elements for IE clients.
    If you use :hover on non-anchor elements, test the page in IE7 and IE8 to be sure your page is usable. If you find that :hover is causing performance issues, consider conditionally using a JavaScript onmouseover event handler for IE clients.

    Additional resources

    For more details on efficient CSS rules with Mozilla, see Writing Efficient CSS for Use in the Mozilla UI.
    For complete information on CSS, see the Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. For information on CSS selectors specifically, see Chapter 5.
  12. admin

    admin Mai Văn Hải Staff Member

    Avoid CSS expressions
    CSS expressions degrade rendering performance; replacing them with alternatives will improve browser rendering for IE users.

    Note: This best practices in this section apply only to Internet Explorer 5 through 7, which support CSS expressions. CSS expressions are deprecated in Internet Explorer 8, and not supported by other browsers.

    Internet Explorer 5 introduced CSS expressions, or "dynamic properties", as a means of dynamically changing document properties in response to various events. They consist of JavaScript expressions embedded as the values of CSS properties in CSS declarations. For the most part, they are used for the following purposes:

    To emulate standard CSS properties supported by other browsers but not yet implemented by IE.
    To provide dynamic styling and advanced event handling in a more compact and convenient way than writing full-blown JavaScript-injected styles.

    Unfortunately, the performance penalty imposed by CSS expressions is considerable, as the browser reevaluates each expression whenever any event is triggered, such as a window resize, a mouse movement and so on. The poor performance of CSS expressions is one of the reasons they are now deprecated in IE 8. If you have used CSS expressions in your pages, you should make every effort to remove them and use other methods to achieve the same functionality.

    Use standard CSS properties if possible.
    IE 8 is fully CSS-standards-compliant; it supports CSS expressions only if run in "compatibility" mode, but it does not support them in "standards" mode. If you do not need to maintain backwards compatibility with older versions of IE, you should convert any instances of expressions used in place of standard CSS properties to their CSS standard counterparts. For a complete list of CSS properties and IE versions that support them, see the MSDN CSS Attributes Index. If you do need to support older versions of IE in which the desired CSS properties are not available, use JavaScript to achieve the equivalent functionality.
    Use JavaScript to script styles.
    If you are using CSS expressions for dynamic styling, it makes sense to rewrite them as pure JavaScript to both improve performance in IE and get the benefit of supporting the same functionality in other browsers at the same time. In this example given on the MSDN page on Dynamic Properties, a CSS expression is used to center an HTML block whose dimensions can change at runtime, and to re-center that block every time the window is resized:

        <div id="oDiv" style="background-color: #CFCFCF; position: absolute;
         top:expression(document.body.clientHeight/2-oDiv.offsetHeight/2)">Example DIV</div>
    Here's an equivalent example using JavaScript and standard CSS:

          #oDiv { position: absolute; background-color: #CFCFCF;}
        <script type="text/javascript">
         // Check for browser support of event handling capability
          if (window.addEventListener) {
          window.addEventListener("load", centerDiv, false);
         window.addEventListener("resize", centerDiv, false);
          } else if (window.attachEvent) {
          window.attachEvent("onload", centerDiv);
          window.attachEvent("onresize", centerDiv);
          } else {
          window.onload = centerDiv;
          window.resize = centerDiv;
          function centerDiv() {
          var myDiv = document.getElementById("oDiv");
          var myBody = document.body;
          var bodyWidth = myBody.offsetWidth;
          //Needed for Firefox, which doesn't support offsetHeight
          var bodyHeight;
         if (myBody.scrollHeight) 
         bodyHeight = myBody.scrollHeight;
         else bodyHeight = myBody.offsetHeight;
          var divWidth = myDiv.offsetWidth;
          if (myDiv.scrollHeight)
           var divHeight = myDiv.scrollHeight;
           else var divHeight = myDiv.offsetHeight;
         myDiv.style.top = (bodyHeight - divHeight) / 2;
          myDiv.style.left = (bodyWidth - divWidth) / 2; 
    If you are using CSS expressions to emulate CSS properties that aren't available in earlier versions of IE, you should provide JavaScript code for those cases with a version test to disable it for browsers that do support CSS. For example, the max-width property, which forces text to wrap around at a certain number of pixels, was not supported until IE 7. As a workaround, this CSS expression provides that functionality for IE 5 and 6:

        p { width: expression( document.body.clientWidth > 600 ? "600px" : "auto" ); }
    To replace the CSS expression with equivalent JavaScript for the IE versions that don't support this property, you could use something like the following:

          p { max-width: 300px; }
        <script type="text/javascript">
          if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) < 7))
          window.attachEvent("onresize", setMaxWidth);
          function setMaxWidth() {
          var paragraphs = document.getElementsByTagName("p");
          for ( var i = 0; i < paragraphs.length; i++ ) 
          paragraphs[i].style.width = ( document.body.clientWidth > 300 ? "300px" : "auto" );
  13. akiana

    akiana New Member

    Hướng dẫn này nếu được translate sang Tiếng Việt thì hay biết mấy... :cry:
  14. hunglvcntt

    hunglvcntt New Member

    cái này hướng dẫn tối ưu css thôi bạn :) . dùng google translate đi

Chia sẻ trang này