jQuery – Add jQuery to head if not already loaded

Jquery add jquery to head if not already loaded image

Ain’t got no jQuery in your WordPress, just add it!

What it does…

Loads jQuery into your page, if it’s not already loaded.

How it does it…

Adds a javascript to your WordPress frontend that checks if `window.jQuery` is defined, if not it attempts to add jQuery from the source of your choosing.

Download JSON for importing into Code Snippets Pro

See the code…

// Use WP jQuery or load it manually
// from: https://snipsnip.pro/s/145
window.addEventListener('DOMContentLoaded', function(){
	if (!window.jQuery) {
		let jQueryScript = document.createElement('script');
		jQueryScript.setAttribute('id','snippet-jq'); 
        // Use any of these sources as you wish
		// jQueryScript.setAttribute('src','https://code.jquery.com/jquery-3.6.0.min.js');
		// jQueryScript.setAttribute('src','https://code.jquery.com/jquery-latest.min.js'); 	 
		// jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js'); 
		jQueryScript.setAttribute('src','https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js'); 
		document.head.appendChild(jQueryScript);
		console.log('jQuery not found. Loaded by snippet.');
  } else {
		console.log('Using default WordPress jQuery.');
  }
});