Kriuchko
1/8/2019 - 8:46 AM

Подключение js defer js

Wordpress enqueue javascript defer


// Fonts
  wp_enqueue_style( 'google_web_fonts', 'https://fonts.googleapis.com/css?family=Muli:300,400,500%7cPoppins:300,400,600,700&display=swap' );

  // Loads our main stylesheet.
  wp_enqueue_style( 'trlvr-style', get_stylesheet_uri(), array() );

  // Implementation stylesheet.
  wp_enqueue_style( 'trlvr-theme', get_template_directory_uri() . '/theme.css', array() );

  if( function_exists('get_field') ) {
    $google_api_key = get_field( 'google_api_key', 'option' );
  }

  if( !empty($google_api_key) ) {
    wp_enqueue_script( 'trlvr-googleapis', 'https://maps.googleapis.com/maps/api/js?key='.$google_api_key );
  }

-------------------------------
<?php wp_enqueue_script("jquery"); ?>
<?php wp_head(); ?>

<?php if ( is_singular() ) wp_enqueue_script( 'theme-comment-reply', get_bloginfo('template_url')."/js/comment-reply.js" ); ?>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/jquery.main.js" ></script>

——————————————————————————————

<?php wp_enqueue_script("jquery"); ?>
<?php wp_head(); ?>

<?php if ( is_singular() ) wp_enqueue_script( 'theme-comment-reply', get_stylesheet_directory_uri()."/js/comment-reply.js" ); ?>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/bootstrap.min.js" defer></script>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/jquery.main.js" defer></script>

//----------------- defer wp wp_enqueue_script defer

https://matthewhorne.me/defer-async-wordpress-scripts/

function add_async_attribute($tag, $handle) {
    if ( 'my-js-handle' !== $handle )
        return $tag;
    return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);

function add_defer_attribute($tag, $handle) {
   // add script handles to the array below
   $scripts_to_defer = array('my-js-handle', 'another-handle');
   
   foreach($scripts_to_defer as $defer_script) {
      if ($defer_script === $handle) {
         return str_replace(' src', ' defer="defer" src', $tag);
      }
   }
   return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);