2

I'm trying to add a tweet button to my node.tpl.php in Drupal 6 - https://dev.twitter.com/docs/tweet-button.

I literally place the html+javascript within node.tpl like so:

<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script><

The result is a flickering button every time I refresh, so I'm thinking the javascript is loading incorrectly?

Ideally, I'd like to load the javascript within page.tpl.php, and ensure that it applies to node.tpl, but it doesn't appear to be working. I've also tried loading it using drupal_add_js within template.php various preprocessor methods.

I rather not use any of the social media modules - such as AddToAny, ShareThis, or ServiceLinks - partly because I feel this should be cut and dry w/o module dependency.

So I guess my question is - what is the best way to load that twitter javascript code within node.tpl to avoid the flickering button?

1 Answer 1

2

Do not place the <script> tag in node.tpl.php because it will repeat if multiple nodes are arranged to appear in a single page.

Use following code to add js in page and call this function in hook_init() or in your page's callback function.

drupal_add_js('<script>...</script>',array(
  'type' => 'inline', 
  'scope' => 'footer'
));
1
  • I'll lose some points for this, but something isn't sitting right. Let's say I don't want to use hook_init() in a custom module to make this call, and instead add it to my theme - I couldn't get your above code to work correctly within HOOK_preprocess_page within my themes template.php. I think part of the reason is that the custom theme we're using doesn't print javascripts out in footer, only header or Drupal.setting. Even if I change your code to address those scopes, I can't get the script to load anywhere. I'll research "page's callback" function a bit more, but any hints?
    – Robbase
    May 31, 2012 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.