Skip to content

Conditionally load javascript based on whether a template part is in use

Chris Reynolds edited this page Jul 23, 2015 · 2 revisions

Quite often, we want to be able to conditionally load javascript based on whether a certain thing is loaded on the page or not. Page Builder makes this super easy.

Let's say we have a template part that required jquery-flipster. Instead of hooking our function that enqueues the jquery-flipster js file to wp_enqueue_scripts, we can hook it to wds_page_builder_after_load_parts. This action fires after all the template parts have been loaded. We also have a helper function, get_page_builder_parts() which returns an array of Page Builder part slugs but only after all the parts have been loaded. This is perfect, because it gives us exactly the information we need.

###Example

	add_action( 'wds_page_builder_after_load_parts', 'load_flipster' );

	/**
	 * Function to conditionally enqueue the flipster js based on whether the template part
	 * is in use on the page.
	 * @since  0.1.0
	 * @return void
	 */
	function load_flipster() {
		$parts = get_page_builder_parts();
		// only load flipster on pages that use the coverflow part
		if ( in_array( 'coverflow', $parts ) ) {
			wp_enqueue_script( 'jquery-flipster', $this->url . '/assets/bower/jquery-flipster/dist/jquery.flipster.min.js', array( 'jquery' ), '20150723', true );
		}
	}

In the example above, we're looking for a template part named part-coverflow.php. The load_flipster function is hooked to the wds_page_builder_after_load_parts action which, as the name implies, fires after all the template parts have loaded. We load an array of those loaded template parts into a variable with get_page_builder_parts and then check the array for the part we are looking for. If it's there, we're enqueuing our flipster javascript file in the footer.

💥 Easy-peasy.

Now, you could always add a wp_enqueue_script inside the template part if you wanted to. Besides being kind of ugly, this means that code lives in the theme. Using the method described above, you can leave the theme out of it, and do it all inside a plugin -- whichever plugin is actually loading the javascript you're enqueuing.