QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads WordPress Enqueue Scripts/Styles only if Widget is Active

WordPress Enqueue Scripts/Styles only if Widget is Active

You should’t load you widget styles and scripts on frontend always. Enqueue them only if widget is active. We can check if widget is active or not using is_active_widget function inside Widget constructor.

Here is the example code

<?php

function load_scripts()
{
    wp_enqueue_script('raphael', plugin_dir_url( __FILE__ ) . 'js/raphael.js', array(), '1.0.0', true);
}

class Custom_Widget extends WP_Widget
{
    public function __construct()
    {
        //enqueue CSS and JS on frontend only if widget is active.
    if(is_active_widget(false, false, $this->id_base))
    {
            add_action('wp_enqueue_scripts', 'load_scripts');
    }
    }
}
Dec 15, 2014Narayan Prusty
Create a Music Player App using Intel XDKPass Variables from WordPress to JavaScript
Comments: 1
  1. Jake
    6 years ago

    Good example showing proper use of wp_enqueue_scripts action rather than arbitrarily calling wp_enqueue_script(), though I’d put load_scripts() as a closure to keep functionality together (which you can do from PHP 5.4, which almost every host will run nowadays).

    Shame your ad-block-blocker seems to detect false positives so the only way of viewing your page is to stop it loading before it has completely.

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago 1 Comment WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • Login User into WordPress without Password
  • WordPress Plugin Activation, Deactivation and Uninstall Hooks
  • WordPress Default Widgets CSS Classes
  • WordPress Custom PHP, JS and CSS Plugin
  • Pass Variables from WordPress to JavaScript
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license