Web page content optimization management and performance skills

Source: Internet
Author: User
Tags base64 encode css preprocessor

Date: 2013-8-14 Source: gbin1.com

In retrospect, we had to spend a lot of time optimizing the page content (images, CSS, and so on). Now users have faster Internet connections, we seem to be able to use larger images or larger Flash files that contain videos or images. However, with the rise of mobile development, we are back to the embarrassment of the past. Website optimization is very important. We need to download less content and respond quickly, so that we can load applications more quickly.

Image: controlled at proper size

Most of the time, we use the same image on different websites, such as an online store. All products have an overview image. For example, there are three pages to describe the product. The first page shows the product list, the second page shows the product details, and the third page shows the original product size diagram. Therefore, we need three images of different sizes. If you use a file to put it on three different pages, the browser will automatically load the full size of the picture, even the list page, in fact, the list page only needs 200x200 size picture. If the size of the original file is about 1 MB and there are 10 product introductions on each page, you need to download 10 MB of resources. This is ineffective. If possible, try to be different for your website
Allows users to download fewer resources. It is also good to take screen resolution into account. If someone uses an iPhone to open your website page, there is no need to display pictures of the size of your computer on your mobile phone. You just need to adjust the size of your mobile phone screen. With CSS media queries, You can compress the image to a smaller size and send it out:

@media only screenand (min-device-width : 320px) and (max-device-width : 480px) {    .header {        background-image: url(../images/background_400x200.jpg);    }}
Compression

It is often not enough to control the proper size when transmitting images. Many file formats can be compressed a lot without losing the truth. There is a type of application that can achieve this effect. For example, Photoshop has a good function called Save for Web and devices:

In this dialog box, there are multiple options, the most important of which is the quality. designing it to around 80% can significantly reduce the file size. Of course, you can also use code to compress files, but I personally prefer to use ps. The following is a simple example written in PHP:

function compressImage($source, $destination, $quality) {    $info = getimagesize($source);    switch($info['mime']) {        case "image/jpeg":            $image = imagecreatefromjpeg($source);            imagejpeg($image, $destination, $quality);        break;        case "image/gif":            $image = imagecreatefromgif($source);            imagegif($image, $destination, $quality);        break;        case "image/png":            $image = imagecreatefrompng($source);            imagepng($image, $destination, $quality);        break;    }}compressImage('source.png', 'destination.png', 85);
Sprite

One way to increase application performance is to reduce the number of requests on the server. Each new image represents the number of requests. One way is to combine several images into one. The merged image is called a sprite. You can change the position of the background layer in CSS to display the images of specific parts accurately. For example, Twitter Bootstrap uses sprites to guide internal icons:

In CSS, you can refer to the following method to display your sprite section:

.icon-edit {    background-image: url("../img/glyphicons-halflings-white.png");    background-position: -96px -72px;}
Ultra-high-speed cache

Browser ultra-high-speed cache is very useful. Although sometimes it may cause some very interesting situations during development, it does help improve the performance of your website. The ultra-high-speed cached content of all browsers includes images, JavaScript, or CSS. There are several ways to control the cache. I suggest you read this article. In general, you can set the title to control the effect:

$expire = 60 * 60 * 24 * 1;// seconds, minutes, hours, daysheader('Cache-Control: maxage='.$expire);header('Expires: '.gmdate('D, d M Y H:i:s', time() + $expire).' GMT');header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
Pre-read

HTML 5 is improving every day. There is a good function called pre-reading, which allows the browser to download the resources you need immediately in advance:

<link rel="prefetch" href="/images/background.jpg">

Data URI scheme/inline Image

A few years ago I developed a simple web page that only contains one HTML folder, but of course it should include some images I need. The data URI solution helped me solve the problem. Our idea is to convert an image into a base64 encoded string and place it in the IMG tag in the src attribute, for example:

 

In this way, your image is actually stored in HTML and an HTTP request is saved. The larger your image, the longer the string. The following is an example of converting a simple PHP script image to a base64 string:

$picture = fread($fp,filesize($file));fclose($fp);// base64 encode the binary data, then break it// into chunks according to RFC 2045 semantics$base64 = base64_encode($picture);$tag = '';$css = 'url(data:image/jpg;base64,'.str_replace("\n", "", $base64).'); ';

In some cases, this method is quite useful, but please note that it is not compatible with IE.

CSS

I think writing CSS is like writing code. You also need an organizational model to define different sections and relationships. Therefore, I think CSS management is very important. Each part of the application should have a corresponding pattern and be well standalone. Different contents can be effectively managed in different folders, but there are also problems. It is not easy to use the @ import status method because every @ import operation means that a new request is sent to the server. If you have 20 different. CSS files, it is equivalent that the browser needs to send 20 requests. The browser does not display the page before rendering/downloading all content. If your .css file is lost or too large, the loading time of the page by the browser will be greatly extended.

Use a CSS Preprocessor

The CSS Preprocessor can solve the above problems. You can save different folders in the same way. The Preprocessor can generate a. CSS file at the end of the folder. In fact, it provides a series of very helpful functions such as variables, nested blocks, mixing and inheritance. The code looks similar to CSS, but it is actually well formatted and structured. There are several easy-to-use pre-processors-sass, less, and stylus. The following is an example written in less mode:

.position(@top: 0, @left: 0) {    position: absolute;    top: @top;    left: @left;    text-align: left;    font-size: 24px;}.header {    .position(20px, 30px);    .tips {        .position(10px, -20px);    }    .logo {        .position(10px, 20px);      }}

Run to generate:

.header {    position: absolute;    top: 20px;    left: 30px;    text-align: left;    font-size: 24px;}.header .tips {    position: absolute;    top: 10px;    left: -20px;    text-align: left;    font-size: 24px;}.header .logo {    position: absolute;    top: 10px;    left: 20px;    text-align: left;    font-size: 24px;}

If you want to create another button of the same style, but the color is different, you can do this:

.button {    border: solid 1px #000;    padding: 10px;    background: #9f0;    color: #0029FF;}.active-button {    .button();    color: #FFF;}
Efficient CSS

In general, most developers have not considered CSS efficiency issues. The efficiency of CSS is reflected in page rendering. If the mode is inefficient, the application runs slowly on the browser. Interestingly, the browser parses the CSS selector from right to left. The following code is even less efficient:

body ul li a {    color: #F000;    text-decoration: none;}

This is because the engine first recognizes all the <A> labels, evaluates each parent element, and finally collects the information in the required mode. You need to know that to improve efficiency, the selector has a sequential order: ID, class, label and general. This means that an element with an ID is rendered faster than an element with only a tag selector. Of course, adding ID to all DOM tree elements is meaningless, but you should check the code and add the places where ID may be added. For example, you can do the following:

ul #navigation li {    background: #ff0232;}

The. Content element is a subset of the Body Tag. In fact, all elements are a subset of the Body Tag. There are two useful links to this topic: developers.google.com and css-tricks.com.

File Size

As we mentioned above, the less code the better, because the browser does not render the page before loading CSS. The following tips can be used to reduce the file size:

Put similar rows

.header {    font-size: 24px;}.content {    font-size: 24px;}

Convert

.header, .content {    font-size: 24px;}

Use stenographer instead

.header {    background-color: #999999;    background-image: url(../images/header.jpg);    background-position: top right;}

Write in the following style

.header {    background: #999 url(../images/header.jpg) top right;}

Reduce the code, that is, to use a tool to remove all spaces and lines, you can use cssoptimiser or minifycss. A common practice is to use this tool on the application server. That is, the language written on the backend. Normally, you can love these components to reduce your code.

Put your CSS file under the

Put your CSS files under the head tab. the browser will first download them.

Javascript

Reduce the number of HTTP requests

As with CSS, it is advantageous to reduce server requests. In most cases, loading JavaScript files does not stop rendering pages, but some parts of the pages are ineffective.

Code reduction

Some gadgets can reduce JavaScript to reduce the file size, but remember that it is necessary to keep the code clean in the development environment. Almost all of these tools change the variable name and convert it into a single-line string, which cannot be debugged.

Try commonjs, AMD,
Requirejs

Javascript itself does not have a mechanism to manage modules. Therefore, these tools are designed to solve this problem. They provide an application interface that you can define and use modules. For example http://requirejs.org /:

<!DOCTYPE html>

Run the script. You can use require () instead of Main. js.

require(["helper/util"], function(util) {    //This function is called when scripts/helper/util.js is loaded.    //If util.js calls define(), then this function is not fired until    //util's dependencies have loaded, and the util argument will hold    //the module value for "helper/util".});

Use namespace

When it comes to code organization, you must mention the namespace. This function is not available in Javascript, but you can implement it through several lines of code. For example, if you want to develop an MVC framework, you can use the following methods:

var model = function() { ... };var view = function() { ... };var controller = function() { ... };

The above code is not enough, and it is easy to conflict with other lines of code. Therefore, you need to group them as independent objects (namespaces) as follows to protect the overall framework:

var MyAwesomeFramework = {    model: function() { ... },    view: function() { ... },    controller: function() { ... }}
Follow the Design Pattern

Pipeline script is popular because it contains a large number of examples. Reusable Design Patterns are solutions to common programming problems. Following certain design patterns can help you better design applications. If I write them all down, I guess they will all be able to publish a book, so here I will only write some examples:

Constructor Mode

Use this mode to build a specific object instance:

var Class = function(param1, param2) {    this.var1 = param1;    this.var2 = param2;}Class.prototype = {    method:function() {        alert(this.var1 + "/" + this.var2);    }};

Or:

function Class(param1, param2) {    this.var1 = param1;    this.var2 = param2;    this.method = function() {        alert(param1 + "/" + param2);    };}; var instance = new Class("value1", "value2");
Module Mode

The module mode allows us to create private and public methods. For example, in the following code, the variable _ index and the method privatemethod are private, and the increment and getindex are public.

var Module = (function() {    var _index = 0;    var privateMethod = function() {        return _index * 10;    }    return {        increment: function() {            _index += 1;        },        getIndex: function() {            return _index;        }    };      })();
Observer Mode

This mode can be seen when event subscription and dispatch occur. The observer is interested in something related to a specific object. Once an action occurs, the observer is notified. The following example shows how to increase the observer of a user object:

var Users = {    list: [],    listeners: {},    add: function(name) {        this.list.push({name: name});        this.dispatch("user-added");    },    on: function(eventName, listener) {        if(!this.listeners[eventName]) this.listeners[eventName] = [];        this.listeners[eventName].push(listener);    },    dispatch: function(eventName) {        if(this.listeners[eventName]) {            for(var i=0; i&lt;this.listeners[eventName].length; i++) {                this.listeners[eventName][i](this);            }        }    },    numOfAddedUsers: function() {        return this.list.length;    }} Users.on("user-added", function() {    alert(Users.numOfAddedUsers());}); Users.add("Krasimir");Users.add("Tsonev");
Function connection mode

This mode can be used to organize public interfaces of modules. Save time and improve readability:

var User = {    profile: {},    name: function(value) {        this.profile.name = value;        return this;    },    job: function(value) {        this.profile.job = value;        return this;    },    getProfile: function() {        return this.profile;    }};   var profile = User.name("Krasimir Tsonev").job("web developer").getProfile();console.log(profile);

I strongly recommend the book Addy Osmani, which covers all the best resources for designing patterns in JavaScript.

Assets-pack

At the end of this article, I would like to share some ideas about CSS and JavaScript code management on the server. This is a common method to add, merge, narrow, and compile the application logic. There is often a caching mechanism, but everything happens at the same time when the program is running. You may have code logic to process. js or. CSS file requests at the same time, and then provide appropriate content. Behind this process is assembly, compression, and others. In my latest project, I used a tool called assets-pack. It is very useful. I can explain in detail what it can do, but more interesting is how I use this tool. It can only be used in the development mode, not in the code form, or on the server.

My idea is to use this tool only when you are dealing with CSS and JS, it can monitor changes in a specific directory, and then compile/package the code into a single file. Through this step, you do not need to consider compression or assembly. All you have to do is send compiled static files to users. This increases the performance of the application because it can only provide static files, which of course makes things easier. You do not need to set any servers or implement unnecessary logic.

The following describes how to install and use assets-Pack:

npm install -g assetspack
Usage

This module can be configured with JSON. When it is called through the command line, you should put the settings in the. JSON file.

Use command line

Create the assets. JSON folder and execute the following code in the same directory:

assetspack

If you want to use another name or use another directory:

assetspack --config [path to json file]

Code Format

var AssetsPack = require("assetspack");var config = [    {        type: "css",        watch: ["css/src"],        output: "tests/packed/styles.css",        minify: true,        exclude: ["custom.css"]    }];var pack = new AssetsPack(config, function() {    console.log("AssetsPack is watching");});pack.onPack(function() {    console.log("AssetsPack did the job"); });
Configuration

The configuration should be a valid JSON file/object. The following is an array of objects:

[    (asset object),    (asset object),    (asset object),    ...]

Asset object

The basic structure of asset object is as follows:

{    type: (file type /string, could be css, js or less for example),    watch: (directory or directories for watching /string or array of strings/),    pack: (directory or directories for packing /string or array of strings/. ),    output: (path to output file /string/),    minify: /boolean/,    exclude: (array of file names)}

The pack attribute is not mandatory. If it is lost, its values are equal. By default, the reduction is a false attribute.

The following are some examples:

Packing CSS

{    type: "css",    watch: ["tests/data/css", "tests/data/css2"],    pack: ["tests/data/css", "tests/data/css2"],    output: "tests/packed/styles.css",    minify: true,    exclude: ["header.css"]}

Packing Javascript

{    type: "js",    watch: "tests/data/js",    pack: ["tests/data/js"],    output: "tests/packed/scripts.js",    minify: true,    exclude: ["A.js"]}

Packing. Less files

Packing. Less files is a bit different. The pack attribute is mandatory based on your entry point. You should import all other. Less files. The exclusion attribute is invalid here.

{    type: "less",    watch: ["tests/data/less"],    pack: "tests/data/less/index.less",    output: "tests/packed/styles-less.css",    minify: true}

If you have other issues, you can view the tests/packing-less.spec.js in the source code (GitHub) Library

Compressing files in other formats

Assets-pack applies to all file formats. For example, you can combine HTML templates and a simple file in the following ways:

{    type: "html",    watch: ["tests/data/tpl"],    output: "tests/packed/template.html",    exclude: ["admin.html"]}

One thing to note is that the magnification is not reduced here.

Conclusion

As front-end web developers, we should try our best to provide users with the best performance. The above tips should not cover the Organization and performance skills of all assets, but they are commonly used.

Via
Geek tag

Source: web page content optimization management and performance skills

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.