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 633 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:
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…
Pro
Grid.js in Bricks

Grid.js in Bricks

This Pro tutorial provides the steps to use Grid.js in a WordPress site powered by Bricks builder. Grid.js is a lightweight and performant JavaScript library…
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:
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:
Auto-switching Bricks Tabs

Auto-switching Bricks Tabs

How to switch tabs every x seconds when the tabs element is scrolled into view.
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:
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
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: