31st Jul '23
/
0 comments

Loading External Scripts in WordPress With Defer Attribute

The next major version of WordPress, 6.3 includes a loading strategy for scripts so we can easily specify that the scripts have defer or async attributes in the script tag HTML.

This page on Make WordPress Core provides the details.

Below is a simplified version of the same.

When enqueuing (putting stuff in a queue for WordPress to load) external JS scripts, it is recommended to do so in the header (before closing head tag) with defer attribute added to the script tags.

Example: Below code in child theme’s functions.php enqueues Splide.

add_action( 'wp_enqueue_scripts', function() {
		wp_enqueue_script(
			'splide',
			esc_url( 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js' ),
			[],
			'4.1.4',
			[ 'strategy' => 'defer' ],
		);
} );

I prefer placing the .js files in child theme’s assets/js directory in which case the code would be:

add_action( 'wp_enqueue_scripts', function() {
		wp_enqueue_script(
			'splide',
			esc_url( get_stylesheet_directory_uri() . '/assets/js/splide.min.js' ),
			[],
			'4.1.4',
			[ 'strategy' => 'defer' ],
		);
} );

WordPress versions prior to 6.3 will load the script in the footer w/o defer.

Below is a complete example when using Bricks builder.

Note: In practice though this is not needed in Bricks because it comes with a pretty decent “Slider (Nestable)” element and if you need the full range of options via the various controls in the Bricks editor, you have the excellent Pro Slider in our BricksExtras. Both these elements utilize SplideJS. The point though, is to show how to enqueue external scripts and initialize them.

Code in child theme’s functions.php:

/**
 * Register/enqueue custom scripts and styles
 */
add_action( 'wp_enqueue_scripts', function() {
	// Enqueue your files on the canvas & frontend, not the builder panel. Otherwise custom CSS might affect builder)
	if ( ! bricks_is_builder_main() ) {
		wp_enqueue_style( 'bricks-child', get_stylesheet_uri(), ['bricks-frontend'], filemtime( get_stylesheet_directory() . '/style.css' ) );
		
    if ( is_front_page() ) {
      // Enqueue Splide CSS
      wp_enqueue_style( 'splide', get_stylesheet_directory_uri() . '/assets/css/splide.min.css' );

      // Enqueue Splide JS
      wp_enqueue_script(
        'splide',
        esc_url( get_stylesheet_directory_uri() . '/assets/js/splide.min.js' ),
        [],
        '4.1.4',
        [
          'strategy' => 'defer',
          'in_footer' => false
        ],
      );
      
      // Enqueue Splide JS Init
      wp_enqueue_script(
        'splide-init',
        esc_url( get_stylesheet_directory_uri() . '/assets/js/splide-init.js' ),
        [ 'splide' ],
        '1.0.0',
        [
          'strategy' => 'defer',
          'in_footer' => false
        ],
      );
    }
	}
} );

Code in assets/js/splide-init.js:

document.addEventListener("DOMContentLoaded", function () {
  const splide = new Splide("#splide")
  splide.mount()
})

Code in a Code element on a Page that’s set as the static homepage:

<div id="splide" class="splide" role="group" aria-label="Splide Basic HTML Example">
  <div class="splide__track">
		<ul class="splide__list">
			<li class="splide__slide"><img src="https://splidejs.com/images/slides/general/01.jpg" alt="Sample Slide 01"></li>
			<li class="splide__slide"><img src="https://splidejs.com/images/slides/general/02.jpg" alt="Sample Slide 02"></li>
			<li class="splide__slide"><img src="https://splidejs.com/images/slides/general/03.jpg" alt="Sample Slide 03"></li>
		</ul>
  </div>
</div>
Get access to all 630 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

How to Create a Grid Slider in Bricks

How to Create a Grid Slider in Bricks

In this tutorial, we'll learn how to create multiple rows and columns inside the default nested slider of Bricks. Introduction A user recently asked in…
Categories:
How to sync two nestable sliders in Bricks

How to sync two nestable sliders in Bricks

In this tutorial, we'll learn how to sync two nestable sliders in Bricks: one will be the main slider and the other one will be…
Categories:
Pro
WP Grid Builder Filters inside Bricks’ OffCanvas

WP Grid Builder Filters inside Bricks’ OffCanvas

This Pro tutorial provides the steps to move WP Grid Builder's filters inside the Bricks' native Offcanvas on smaller viewport widths. Let's work with the…
Auto-switching Bricks Tabs

Auto-switching Bricks Tabs

How to switch tabs every x seconds when the tabs element is scrolled into view.
Categories:
Pro
Post Title at a Different Location on Image Hover

Post Title at a Different Location on Image Hover

This Pro tutorial provides the steps to update the text of a sticky div with the title of the post that is hovered on the…
Categories:
Pro
[WooCommerce] Sticky on Scroll Add to Cart section in Bricks

[WooCommerce] Sticky on Scroll Add to Cart section in Bricks

Setting up a sticky section that fades in when scrolling down and fades away when scrolled to the top.
Categories:
Setting Active Tab in Bricks’ Tabs (Nestable) Element

Setting Active Tab in Bricks’ Tabs (Nestable) Element

With Bricks' Nestable tab element, here's how we can set which tab is active by default.
Categories:
Pro
tsParticles in Bricks

tsParticles in Bricks

Updated on 5 Aug 2023 This Pro tutorial provides the steps to set up tsParticles, a lightweight TypeScript (uses JavaScript) library for creating particles as…
Categories: