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 525 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

Pro
Button-specific HTML in Bricks Popup

Button-specific HTML in Bricks Popup

In the Bricks Facebook group a user asks: I need to create popups to expend the text (eg. read more). I wonder if I have…
Categories:
How to disable smooth scroll in Bricks

How to disable smooth scroll in Bricks

In certain situations like using ScrollSmoother, you may be looking to disable smooth scrolling functionality that’s built into Bricks.
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:
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:
How to change the text of an element based on breakpoints without creating duplicated content

How to change the text of an element based on breakpoints without creating duplicated content

In this tutorial, we'll learn how to dynamically change the text of a basic text element based on the viewport width in Bricks. Introduction Sometimes…
Categories:
Enqueueing a JavaScript File in Bricks

Enqueueing a JavaScript File in Bricks

Bricks child theme's functions.php comes with code to enqueue (load) style.css on the front end. What if you want to load a custom JavaScript file…
Categories:
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:
Pro
Opening Submenus with Click Instead of Hover in Bricks

Opening Submenus with Click Instead of Hover in Bricks

This Pro tutorial provides the code for opening submenus with click instead of hover in Bricks. Step 1 Add this in child theme's style.css: Step…
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: