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

Leave the first comment

 

Related Tutorials..

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:
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:
McDonald’s Order Promise Analogy

McDonald’s Order Promise Analogy

From the JavaScript course I am doing now: A Promise is like placing an order at a restaurant. You receive a ticket (Promise object) that…
Categories:
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
[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
Switching Tabs on Hover in Bricks

Switching Tabs on Hover in Bricks

This Pro tutorial shows how to make the tabs of Tabs (Nestable) elements active on hover in Bricks. Step 1 Add one or more Tabs…
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
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: