Статьи

Ленивые кнопки загрузки социальных медиа

Поскольку скорость загрузки страниц очень важна для успеха веб-сайтов, вам нужно постараться максимально ускорить все области вашего веб-сайта. Одной из функций, которыми обладает большинство веб-сайтов, являются кнопки социальных сетей , которые позволяют посетителям легко делиться вашими статьями в своих любимых социальных сетях. Это также позволяет вашим посетителям видеть, сколько раз страница была опубликована в каждой из социальных сетей.

Проблема с этими кнопками социальных сетей состоит в том, что им приходится делать множество HTTP-запросов через AJAX, чтобы получить всю информацию, необходимую для отображения кнопки. Они будут получать изображения для кнопок и количество раз, когда страница была опубликована. Обычно есть по крайней мере три основные социальные сети: Facebook, Twitter и Google Plus, но также могут быть Pinterest, LinkedIn и многие другие. Со всеми этими различными кнопками социальных сетей на странице может быть много HTTP-запросов, чтобы получить всю информацию для страницы.

Каждый из этих HTTP-запросов влияет на общее время загрузки страницы, поэтому важно постараться максимально сократить их. Один из способов сделать это — удалить кнопки по умолчанию и заменить их простой ссылкой на общий ресурс. Это не покажет вам, сколько людей уже поделились этой страницей, что может быть важно для вашего бренда, чтобы показать, что многие люди делятся этими статьями. Но если это не важно для вашего сайта, то вы можете легко заменить их ссылками.

Если вы хотите использовать кнопки социальных сетей по умолчанию, тогда один вариант — использовать отложенную загрузку, чтобы отправлять HTTP-запросы только тогда, когда это необходимо . Это можно сделать, прокручивая страницу вниз и располагая кнопки социальных сетей в конце страницы и загружая их только тогда, когда вы находитесь в нижней части страницы. Вы даже можете скрыть кнопки по умолчанию и загружать их только нажатием кнопки, а затем делать HTTP-запросы для загрузки социальных кнопок.

Следующий код покажет вам, как можно лениво загрузить 4 основные кнопки социальных сетей Twitter, Facebook, Google+ и LinkedIn .

Асинхронная загрузка Javascript

Другое решение для загрузки кнопок социальных сетей — убедиться, что Javascript загружается асинхронно, это означает, что Javascript будет загружаться и работать, но не повлияет на загрузку остальной части страницы. Это означает, что ваша страница будет только немного замедляться из-за кнопок социальных сетей, но им по-прежнему необходимо отправлять HTTP-запросы и использовать полосу пропускания на вашей странице.

Для асинхронной загрузки файла Javascript вы можете использовать следующий код.

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript"
scriptTag.src = "http://www.domain.com/social_media.js";
scriptTag.async = true;
document.getElementsByTagName("head")[0].appendChild(scriptTag);

Это создаст новый тег сценария, добавит JavaScript социальной сети в атрибут src и добавит тег внутри заголовка документа.

Я предпочитаю использовать jQuery при работе с Javascript, он просто делает вещи намного проще. В JQuery есть удобный метод getScript (), который выполняет вышеизложенное, но с меньшим количеством строк кода.

(function() {
     $.getScript('http://www.domain.com/social_media.js');
});

Теперь мы можем использовать эту технику на следующих примерах, чтобы показать, как мы будем загружать кнопки социальных сетей на кнопках, которые затем будут загружаться в Javascript для кнопок. Если Javascript уже загружен, следующий код покажет вам, какие функции вы можете вызвать для загрузки в социальные кнопки с помощью их API.

Посмотрите демо, чтобы увидеть, что мы можем создать.

демонстрация

Кнопка Twitter

Существует два способа загрузки в каждую из социальных кнопок: если HTML-код для кнопки уже находится в DOM, все, что вам нужно сделать, это загрузить Javascript с помощью метода $ .getScript () . Когда этот Javascript загружен, он будет искать правильный HTML и превращать его в кнопки Twitter .

HTML-код, необходимый для кнопок Twitter, следующий:

<a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal"></a>

С помощью кнопки Twitter HTML находится в DOM, и теперь мы можем загрузить Javascript с помощью метода $ .getScript () .

$.getScript('http://platform.twitter.com/widgets.js');

Когда этот Javascript загружен, он будет искать все ссылки Twitter и превращать их в кнопки Twitter.

Но если Javascript уже загружен на страницу, и вы добавляете новые ссылки твиттера на страницу, вам нужен способ снова запустить скрипт загрузки виджета, чтобы Twitter искал ссылки, чтобы превратить их в кнопки.

Когда JavaScript Javascript загружается на страницу, он создает объект с именем twttr для этого объекта, и у него есть метод, который можно использовать для повторной загрузки виджетов снова. Чтобы снова запустить скрипт загрузки Twitter, вы можете использовать следующий код.

if (typeof (twttr) != 'undefined'){
     twttr.widgets.load();
}

Из этих двух методов мы можем создать функцию, которая будет проверять, установлен ли объект twttr , если нет, то мы можем загрузить файл JavaScript Javascript, если он установлен, то мы можем вызвать функцию загрузки, чтобы отобразить все кнопки Twitter.

function loadTwitter()
{
    if (typeof (twttr) != 'undefined'){
        twttr.widgets.load();
    } else {
        $.getScript('http://platform.twitter.com/widgets.js');
    }
}

Кнопка Facebook

Опять же, с помощью кнопки Facebook есть два способа загрузки кнопок, вы можете либо загрузить Javascript, который затем будет искать HTML-код кнопок и превращать их в кнопки Facebook. Вы также можете загрузить кнопку, вызвав метод Javascript.

Существует несколько способов добавления HTML-кода для кнопки Facebook, ниже приведен лишь один из способов добавления HTML-кода для кнопки Facebook.

<div class="fb-like" data-layout="button_count" data-send="false" data-show-faces="false" data-width="90"></div>

Имея HTML-код на странице, вы теперь можете загружать его в Javascript, при этом он будет искать HTML-код и превращать его в кнопку Facebook. Ниже показано, как вы можете использовать метод $ .getScript () для загрузки в JavaScript Javascript. Второй параметр метода $ .getScript () — это функция обратного вызова, которая запускается после загрузки скрипта. Внутри этой функции мы можем создать экземпляр объекта Facebook, который затем превратит HTML в кнопку Facebook.

$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
     FB.init({ status: true, cookie: true, xfbml: true });
});

If the Javascript is already loaded on the page and we create new HTML elements which aren’t affected by the FB object then we need a way of loading the object again to turn the HTML into Facebook buttons. When we load in the Facebook Javascript it will create an object called FB. We can then check if this object exists and if it does already exist then we can recall the init() method which will reload the Facebook buttons.

if (typeof (FB) != 'undefined') {
     FB.init({ status: true, cookie: true, xfbml: true });
}

By using these two methods we can create a function to call each time we want to reload the Facebook buttons. Using this method means it doesn’t matter if the Javascript is loaded or not the function will check and reload the buttons again for you. This first checks to see if the FB object exists if it does then it will simple re-run the init() method, else it will load in the Javascript and call the init() method on the FB object.

function loadFacebook()
{
    if (typeof (FB) != 'undefined') {
        FB.init({ status: true, cookie: true, xfbml: true });
    } else {
        $.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
            FB.init({ status: true, cookie: true, xfbml: true });
        });
    }
}

Google Plus Button

The Google Plus button also works in the same way as the others, there is HTML to add on to identify which ones are buttons, there is Javascript you can use to load into the page and a method on the Google API object to render the buttons again.

Below is the HTML that you need to use for the Google plus button, the important attribute to include is the class=»g-plusone», this is what we will use to class the render method on the Google API.

<div class="g-plusone" data-annotation="inline" data-size="medium" data-width="120"></div>

If the HTML is on the page then we can call in the Google plus Javascript, when this is loaded it will check for the HTML button on the page, if they are found then it will turn these into Google plus buttons.

$.getScript('https://apis.google.com/js/plusone.js');

Like the other buttons we could have the problem of the Javascript already loaded on the page and then we insert the HTML, the Google API will then not turn this into a Google Plus button without calling the method to render the buttons again. When the Google plus Javascript is loaded on the page it will create an object of gapi, which has a method on it called render() which will allow you to pass in an element to render as the Google plus button.

This means that we can now search for all elements with the class of g-plusone and pass these into the render method, this will then reset all these elements into Google plus buttons.

$(".g-plusone").each(function () {
     gapi.plusone.render($(this).get(0));
});

Using these two methods we can create a function just for Google plus, which will check to see if the gapi object is set, if it is then we can run the render() method on the gapi object which will search for the Google plus class on the HTML and pass this element into the render() method. If the gapi object doesn’t exist then we need to load in the Google plus Javascript file by using the $.getScript() method.

function loadGooglePlus()
{
    if (typeof (gapi) != 'undefined') {
        $(".g-plusone").each(function () {
            gapi.plusone.render($(this).get(0));
        });
    } else {
        $.getScript('https://apis.google.com/js/plusone.js');
    }
}

LinkedIn Button

Just like the other buttons the LinkedIn social button can be rendered by loading in the Javascript file or by using a single render method. The difference with the LinkedIn button is that it doesn’t use a standard HTML tag but will use a Javascript tag in the place where the button will appear.

<script type="IN/Share" data-counter="right"></script>

When this is on the page then we can add the LinkedIn Javascript file which will create the LinkedIn API object IN, when this is loaded it will search for the LinkedIn share button tag and turn this into a LinkedIn button.

$.getScript("http://platform.linkedin.com/in.js");

If the Javascript is already loaded and we want to add a new LinkedIn button to the page then we can use the IN object to call the parse() method, which will turn all the LinkedIn script tags into LinkedIn buttons.

if (typeof (IN) != 'undefined') {
     IN.parse();
}

From these two methods we can create a function that we can call which will check to see if the LinkedIn object is set, if it is already set then we can call the parse() method to render the LinkedIn buttons again. If the object isn’t set yet then we can load in the Javascript needed by using the $.getScript() method. Once this is loaded it will create the IN object that will automatically render the LinkedIn buttons.

function loadLinkedIn()
{
     if (typeof (IN) != 'undefined') {
          IN.parse();
     } else {
          $.getScript("http://platform.linkedin.com/in.js");
     }
}

Demo

In the demo there is a button at the top of screen this is the first time that you load in the Javascript, which will automatically load in all the Javascript files needed and display the buttons.

This will create HTML on the page for the other individual buttons, now when you click on these buttons the Javascript is already loaded so will run the methods to render all the buttons again.

Demo