Как оптимизировать загрузку подключенных файлов javascript

(Ответов: 5, Просмотров: 5315)
  1. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    Я файле header.php подключаю 8 подряд js файлов. Вот часть с начала до конца </head>
    PHP код:
    <!doctype html>
    <html>
    <head>
        <?php if( is_page('contact') ){ ?>
        <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/validat.js"></script> 
        <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script>
        <?php }?>
        <title><?php bloginfo('name');?><?php wp_title();?></title>
        <meta charset="<?php bloginfo('charset')?>">
        <link rel="stylesheet" href="<?php bloginfo('stylesheet_url');?>" type="text/css">
        <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/css/elastislide.css" />
        <link href="<?php bloginfo('template_url'); ?>/css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />
        <link rel="pingback" href="<?php bloginfo('pingback_url');?>">
        <?php
            
    if ( is_singular() && get_option'thread_comments' ) )
            
    wp_enqueue_script'comment-reply' );
        
    ?>
        <?php wp_head(); ?>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery-1.10.2.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/menu.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.lightbox-0.5.pack.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/top_button.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/click_menu.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/validator.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.easing.1.3.js"></script>
        <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.elastislide.js"></script>
    <script type="text/javascript">
    jQuery(function(){
    jQuery(".zoom").lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.6,
        imageLoading: '<?php bloginfo('template_url'); ?>/img/lightbox-ico-loading.gif',
        imageBtnClose: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-close.gif',
        imageBtnPrev: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-prev.gif',
        imageBtnNext: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: 'Изображение',
        txtOf: 'из'
       });
    });
    </script>
    <noscript>
                <style>
                    .es-carousel ul{
                        display:block;
                    }
                </style>
            </noscript>
    </head>
    На сервисе гугл по проверке ускорения загрузки страниц http://developers.google.com/speed/pagespeed/insights/ мне выдало такое сообщение:
    Исправьте по возможности:
    Удалите из верхней части страницы код JavaScript и CSS, блокирующий отображение
    Количество блокирующих скриптов на странице: 8. Количество блокирующих ресурсов CSS на странице: 3. Они замедляют отображение контента.
    Все содержание верхней части страницы отображается только после загрузки указанных далее ресурсов. Попробуйте отложить загрузку этих ресурсов, загружать их асинхронно или встроить их самые важные компоненты непосредственно в код HTML.

    Удалите код JavaScript, препятствующий отображению:
    http://fr3809bb.bget.ru/…nt/themes/B...uery-1.10.2.js
    http://fr3809bb.bget.ru/wp-content/t...oft/js/menu.js
    http://fr3809bb.bget.ru/…etterSoft/j...ox-0.5.pack.js
    http://fr3809bb.bget.ru/…ntent/theme.../top_button.js
    http://fr3809bb.bget.ru/…ntent/theme.../click_menu.js
    http://fr3809bb.bget.ru/…ontent/them...s/validator.js
    http://fr3809bb.bget.ru/…hemes/Bette....easing.1.3.js
    http://fr3809bb.bget.ru/…emes/Better...elastislide.js
    Что это может значить? А также правильно ли так подключать все сверху скрипты, может их нужно подключать некоторые в самом коде перед вызовом.
    Заранее благодарен.
    • 0
  2. Новичок Аватар для Akara
    • Регистрация: 23.11.2011
    • Сообщений: 24
    • Репутация: 15
    SergeyNetIt, подключите вот так

    PHP код:
    <?php 
        wp_head
    ();
        
    wp_enqueue_script('jquery');
        
    wp_enqueue_script('menu'get_template_directory_uri() .'/js/menu.js', array('jquery'));
        
    wp_enqueue_script('lightbox'get_template_directory_uri() .'/js/jquery.lightbox-0.5.pack.js', array('jquery'));
        
    wp_enqueue_script('top_button'get_template_directory_uri() .'/js/top_button.js', array('jquery'));
        
    wp_enqueue_script('click_menu'get_template_directory_uri() .'/js/click_menu.js', array('jquery'));
        
    wp_enqueue_script('validator'get_template_directory_uri() .'/js/validator.js', array('jquery'));
        
    wp_enqueue_script('easing'get_template_directory_uri() .'/js/jquery.easing.1.3.js', array('jquery'));
        
    wp_enqueue_script('elastislide'get_template_directory_uri() .'/js/jquery.elastislide.js', array('jquery'));
        if (
    is_singular() && get_option('thread_comments')) wp_enqueue_script'comment-reply' );
    ?>
    подключение скриптов после wp-head(); выведет их в конце страницы. Плюс я бы объединила некоторые небольшие скрипты в один файл. Например, click_menu.js и top_button.js

    P.S: Плюс стили так же можно объединить в один файл, но все же оставить внутри <head>
    Последний раз редактировалось Akara; 15.01.2014 в 18:43.
    • 0
  3. Дипломник Аватар для Tiefe
    • Регистрация: 17.12.2012
    • Сообщений: 120
    • Репутация: 18
    Если вы используете Wordpress то возможно есть смысл использовать плагины для оптимизации, вроде этого - _http://wordpress.org/plugins/js-css-script-optimizer/
    • 0
  4. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    Akara, подключил, как вы написали - не один скрипт вообще не работает

    ---------- Сообщение добавлено 09:44 ---------- Предыдущее 09:42 ----------

    Akara,вот так
    PHP код:
    <!doctype html>
    <html>
    <head>
        <?php if( is_page('contact') ){ ?>
        <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/validat.js"></script> 
        <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script>
        <?php }?>
        <title><?php bloginfo('name');?><?php wp_title();?></title>
        <meta charset="<?php bloginfo('charset')?>">
        <link rel="stylesheet" href="<?php bloginfo('stylesheet_url');?>" type="text/css">
        <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/css/elastislide.css" />
        <link href="<?php bloginfo('template_url'); ?>/css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />
        <link rel="pingback" href="<?php bloginfo('pingback_url');?>">
        <?php 
        wp_head
    ();
        
    wp_enqueue_script('jquery');
        
    wp_enqueue_script('menu'get_template_directory_uri() .'/js/menu.js', array('jquery'));
        
    wp_enqueue_script('lightbox'get_template_directory_uri() .'/js/jquery.lightbox-0.5.pack.js', array('jquery'));
        
    wp_enqueue_script('top_button'get_template_directory_uri() .'/js/top_button.js', array('jquery'));
        
    wp_enqueue_script('click_menu'get_template_directory_uri() .'/js/click_menu.js', array('jquery'));
        
    wp_enqueue_script('validator'get_template_directory_uri() .'/js/validator.js', array('jquery'));
        
    wp_enqueue_script('easing'get_template_directory_uri() .'/js/jquery.easing.1.3.js', array('jquery'));
        
    wp_enqueue_script('elastislide'get_template_directory_uri() .'/js/jquery.elastislide.js', array('jquery'));
        if (
    is_singular() && get_option('thread_comments')) wp_enqueue_script'comment-reply' );
    ?>
    <script type="text/javascript">
    jQuery(function(){
    jQuery(".zoom").lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.6,
        imageLoading: '<?php bloginfo('template_url'); ?>/img/lightbox-ico-loading.gif',
        imageBtnClose: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-close.gif',
        imageBtnPrev: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-prev.gif',
        imageBtnNext: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: 'Изображение',
        txtOf: 'из'
       });
    });
    </script>
    <noscript>
                <style>
                    .es-carousel ul{
                        display:block;
                    }
                </style>
            </noscript>
    </head>
    • 0
  5. Новичок Аватар для Akara
    • Регистрация: 23.11.2011
    • Сообщений: 24
    • Репутация: 15
    SergeyNetIt,
    без ссылки на сайт сложно сказать, что именно не работает. Попробуйте вот так

    PHP код:
    <!doctype html>
    <html>
    <head>
        <meta charset="<?php bloginfo('charset')?>">

        <title><?php bloginfo('name');?><?php wp_title();?></title>

        <link rel="stylesheet" href="<?php bloginfo('stylesheet_url');?>" type="text/css">
        <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/css/elastislide.css" />
        <link href="<?php bloginfo('template_url'); ?>/css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />
        <link rel="pingback" href="<?php bloginfo('pingback_url');?>">
        
        <?php 
        wp_head
    ();
        
    wp_enqueue_script('jquery');
        
    wp_enqueue_script('menu'get_template_directory_uri() .'/js/menu.js', array('jquery'));
        
    wp_enqueue_script('lightbox'get_template_directory_uri() .'/js/jquery.lightbox-0.5.pack.js', array('jquery'));
        
    wp_enqueue_script('top_button'get_template_directory_uri() .'/js/top_button.js', array('jquery'));
        
    wp_enqueue_script('click_menu'get_template_directory_uri() .'/js/click_menu.js', array('jquery'));
        
    wp_enqueue_script('validator'get_template_directory_uri() .'/js/validator.js', array('jquery'));
        
    wp_enqueue_script('easing'get_template_directory_uri() .'/js/jquery.easing.1.3.js', array('jquery'));
        
    wp_enqueue_script('elastislide'get_template_directory_uri() .'/js/jquery.elastislide.js', array('jquery'));
        if (
    is_singular() && get_option('thread_comments')) wp_enqueue_script'comment-reply' ); 
        if(
    is_page('contact')) {
            
    wp_enqueue_script('validat'get_template_directory_uri() .'/js/validat.js', array('jquery'));
            
    wp_enqueue_script('verif'get_template_directory_uri() .'/js/verif.js', array('jquery'));
        }
    ?>
    </head>
    вот этот кусок перенесите в footer.php и впишите перед </body>
    PHP код:
    <script type="text/javascript">
    jQuery(function(){
    jQuery(".zoom").lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.6,
        imageLoading: '<?php bloginfo('template_url'); ?>/img/lightbox-ico-loading.gif',
        imageBtnClose: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-close.gif',
        imageBtnPrev: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-prev.gif',
        imageBtnNext: '<?php bloginfo('template_url'); ?>/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: 'Изображение',
        txtOf: 'из'
       });
    });
    </script>
    <noscript>
    <style>
        .es-carousel ul{
            display:block;
        }
    </style>
    </noscript>
    и проверьте есть ли в footer.php функция <?php wp_footer(); ?>
    • 0
  6. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    Akara,Вот сайт http://fr3809bb.bget.ru/ .Пока на бесплатном хостинге. Тестирую, перерабатываю, изменяю.
    • 0

Похожие темы

Темы Раздел Ответов Последний пост
Как удалить со страницы код JavaScript & CSS который тормозит её загрузку
Вопросы от новичков 4 03.11.2013 20:51
Как взломать DLE через загрузку аватара
DLE 4 02.06.2013 22:35
Загрузка рекламы тормозит загрузку сайта.
Вопросы от новичков 6 20.11.2011 02:31
Как ускорить загрузку сайта?
Вопросы от новичков 10 30.08.2011 16:34
Как я ускорил загрузку блога в 10 раз
Дайджест блогосферы 1 22.09.2010 02:02

У кого попросить инвайт?

Вы можете попросить инвайт у любого модератора:

Информеры