310 posts
  • Has referred 50+ members
  • Has sold $10,000+ on Envato Market
  • Has been a beta tester for an Envato feature
  • Had an item featured in an Envato Bundle
+7 more
ceasar says

Hai,

I noticed that almost every plugin in wordpress load there css and js files even if not used.

I do it this way

        function hook_plugin_init()
        {
        if (!is_admin()) {
               wp_enqueue_style( 'css file', __FILE__), null, '1', 'all' );
               wp_enqueue_script( 'jquery' );
               wp_enqueue_script('js file', __FILE__), null, '1' , true );
        }
        }

So same issue here. Even when the plugin is not used the code will be loaded.

Is there a way to detect if a plugin is used on a page and only then load the css and js files ?

Thanks

46 posts
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $75,000+ on Envato Market and is now an Elite Author
  • Made it to the Authors' Hall of Fame
  • Sells items exclusively on Envato Market
+3 more
cosmocoder says

If you are using a shortcode then you can detect the presence of the shortcode and then enqueue the scripts. See here for details (note there is an old version and updated version of the method) – http://scribu.net/wordpress/conditional-script-loading-revisited.html

The method to load css is not quite straightforward. One way is to add a an action to “the_posts” hook and look for the presence of the shortcode and if it is present then enqueue the css file. See here – http://beerpla.net/2010/01/13/wordpress-plugin-development-how-to-include-css-and-javascript-conditionally-and-only-when-needed-by-the-posts/. A clear disadvantage of this is that it will only work if your shortcode is used only in posts and not in other places like the sidebar.

310 posts
  • Has referred 50+ members
  • Has sold $10,000+ on Envato Market
  • Has been a beta tester for an Envato feature
  • Had an item featured in an Envato Bundle
+7 more
ceasar says

I see. But then the js will not be loaded in the template header but just above the plugin ? I don’t think that will help to speed things up or make correct html. I will try the above funtion to look where the code will be placed.

46 posts
  • Elite Author: Sold more than $75,000 on Envato Market
  • Has sold $75,000+ on Envato Market and is now an Elite Author
  • Made it to the Authors' Hall of Fame
  • Sells items exclusively on Envato Market
+3 more
cosmocoder says

I see. But then the js will not be loaded in the template header but just above the plugin

No, the js files will not be loaded just anywhere in the page, if you set the last parameter to true in wp_enqueue_script() (http://codex.wordpress.org/Function_Reference/wp_enqueue_script) which will then enable the js files to be loaded just before the closing body tag, and which is actually a recommended practice.

by
by
by
by
by
by