WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Javascript based widget running regardless (3 posts)

  1. atomworks
    Member
    Posted 4 years ago #

    Hello,

    I have a problem with coding widgets. I've done a handful of small ones for private use that I don't want to give out to the public until I'm happy they are up to standard.

    My issue is with widgets that run javascript. Whether I am using that widget on the page or not it is still running the javascript. Is there a tag or some way of coding the plugin so that it only runs my initialisation code if its being used in a sidebar?

    Hope I'm just missing something basic here, but I can't rack down details on this for love nor money.

    Regards,

    Leonard

  2. atomworks
    Member
    Posted 4 years ago #

    Seeing as this was posted before the weekend when the last thing people would be doing is helping out with coding questions I thought I'd tag this shameless bounce message on in hope someone might see it!

  3. atomworks
    Member
    Posted 4 years ago #

    OK... seeing as no one seems to know and digging around Google for hours on end didn't show up anything useful, for anyone that stumbles across this post this is what I did, it may not be relevant to you but if it is I hope it helps.

    It doesn't seem that I can only call the javascript when the widget is being used on that page so I had to come up with a different approach. My plugin used PHP to place a tag in sidebar like this...

    <div id="gallerywidget"></div>

    The javascript (jQuery based) would then search for the tags and put the relevant HTML in there. Regardless of what page it was or if the tags were there the function would be called and it would retrieve Flickr data and the images but not use them... stupid and pointless overhead for any page not using it.

    Simply what I did to remedy it, and this is not perfect but a lot better then it was, was to wrap the innards of the main function that was being called like this...

    function populategallery(){
         if ( jQuery("#gallerywidget").length > 0 ) {
              // FUNCTION CODE
         }
    }

    This meant when the widget wasn't being called, the div tags with the ID weren't being output and so the function effectively would do nothing. It's a vast improvement as I say and I'll be happy to release this plugin using this method but I'll be keeping an eye out for a better way in the future.

Topic Closed

This topic has been closed to new replies.

About this Topic