Welcome to ManageWP.org

Register to share, discuss and vote for the best WordPress stories every day, find new ideas and inspiration for your business and network with other members of the WordPress community. Join the #1 WordPress news community!

×

3 min read Lisa League

Prevent loading unnecessary scripts and styles in WordPress

Make your site load faster, don't load what you don't need.

Prevent loading unnecessary scripts and styles in WordPress

Some plugins, when installed, add about 2 or 3 scripts and stylesheets to every page on your website. This isn’t necessarily a problem but it would be nice to have scripts loaded only on pages that actually need them. Let’s take the popular Contact Form 7 plugin as an example. Most likely, only pages that contain the [contact-form-7] shortcode will need the extra scripts and styles.
The following snippet will check your post content to see if it contains the contact form 7 shortcode. If it doesn’t, it will dequeue the styles and scripts so they will not be loaded. function dvk_dequeue_scripts() { $load_scripts = false; if( is_singular() ) { $post = get_post(); if( strstr($post->post_content, '[contact-form-7 ') ) { $load_scripts = true; } } if( ! $load_scripts ) { wp_dequeue_script( 'contact-form-7' ); wp_dequeue_style( 'contact-form-7' ); } } add_action( 'wp_enqueue_scripts', 'dvk_dequeue_scripts', 99 );
You can, of course, add more logic to the function to detect the necessity of scripts for other plugins as well. You will need to know the handles used to identify the scripts and styles of the plugin and the shortcode.
Be careful when implementing this though. If you’re rendering

Time to resurrect WordPress Snippets til Christmas 2013

Thank you for useful tutorials and markup without which this wouldn't be possible. For an endless supply of graphics and Photoshop resources.
For an endless supply of vector graphics.
The engine behind the power.