Rajeeb Banstola

Rajeeb Banstola


Startups Enthusiast. Loves to code (PHP, JS). Occasional Blogger, wannabe Entrepreneur & Amateur Philosopher

June 2017
S M T W T F S
« Jan    
 123
45678910
11121314151617
18192021222324
252627282930  

Categories


Loading scripts only when widget is active

RajeebTheGreatRajeebTheGreat

This is yet another post on the series of my tasks on how to reduce load time of ColorMag WordPress theme.


The way ColorMag WP theme works, we currently have several sidebar areas and different widgets to place on them. The theme registers more than 6 widgets and some of depend on various scripts to work properly.

For example: Category slider widget of ColorMag theme needs BxSliderJS to display properly on frontend. As of now, theme used to load BxSliderJS in frontend without even checking it is needed or not. Basically the js is being loaded even on 404 page or single page without any slider.

What could have been the best scenario is that the theme checks if any widget which depend on sliderjs is active on site and then loads the script accordingly. That way, one less HTTP request and better page speed.

After a little research I found a function on Codex.

is_active_widget( $callback, $widget_id, $id_base, $skip_inactive );

So how to use is_active_widget function?

This function takes 4 parameters and returns false if the specified widget is not active or returns id of sidebar area in which the specified widget is active.
$callback = widget callback to check
$widget_id = Widget ID
$id_base = Widget Class created by extending WP_Widget
$skip_inactive = whether to check in inactive widgets

This is how I used in theme to load scripts depending upon the need.

It’s pretty straight forward. We are just passing the widget ID there. If widget is active on site then is_active_widget functions returns the sidebar id and then the required js is enqueue on site. Else false is returned and the js is not enqueued anywhere on the site.

Regarding that suffix thing, that’s another way I used to load minified assets on theme to reduce the load time. That’s explained here.

Note: WordPress Codex recommend to run this function after widgets have been initialized in order to be effective. ( at init action or later to be precise )

Startups Enthusiast. Loves to code (PHP, JS). Occasional Blogger, wannabe Entrepreneur & Amateur Philosopher

Comments 0
There are currently no comments.