Hello Friends, I hope you are doing good. Today we are sharing important information about shortcode .
Normally using wordpress shortcode hooks function add_shortcode() we can register new shortcode. We used enqueue CSS/JS file in our shortcode to make content stylish and to add some advance js features.
Mostly all WordPress developers used enqueue script & styles files in general way so enqueue css/js files always load on every page of your website even we have added shortcode only on a single page. so except the shortcode page there are no use of shortcode js/css files on any page. These enqueue js/css files increased the number of request and page size as well and due to this page speed can slow down.
So you need to follow our smart way to load enqueue script/styles only for shortcode pages so that these enqueue files only load when shortcode is present on that page. it will help to reduce number of request on un shortcode page and improve the other pages speed.
please use below sample code and do needful changes as per your requirement.
if(!class_exists('customShortcodeClass')): class customShortcodeClass { /** * Construct the plugin object */ public function __construct() { // register actions add_shortcode( 'myshortcode', array(&$this, 'my_shortcode_func' ) ); // register shortcode style add_action( 'wp_enqueue_scripts', array(&$this, 'my_shortcode_style_func' ) ); } // END public function __construct public function my_shortcode_style_func() { wp_register_style( 'my_shortcode_style', 'STYLE_SHEET_PATH_GOES HERE'); } public static function my_shortcode_func($atts) { $html = 'This is shortcode content'; wp_enqueue_style( 'my_shortcode_style' ); //load shortcode style return $html; } } //init class new customShortcodeClass(); //init endif;