Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append html to <head> with jQuery

I am trying to append a Facebook open graph tag (based on dynamically generated content on the page) to the head of my html.

 $(document).ready(function(){
var stat = $('#random-message').text();
stat = jQuery.trim(stat);

//set facebook Open Graph description
$('head').append('<meta property="og:description" content="'+stat+'"/>');

  });

this by itself is working fine. js fiddle

When I combine it with a dynamically loaded Twitter script (below)

$(document).ready(function(){
var stat = $('#random-message').text();
stat = jQuery.trim(stat);
//set tweet button data text
$('a.twitter-share-button').attr('data-text',stat);

//set facebook Open Graph description
$('head').append('<meta property="og:description" content="'+stat+'"/>');

//insert twitter API Script - problematic
$('#tweet-like').append('<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');

});

it chucks a wobbly. js fiddle In js fiddle, it inserts some special characters into the body, and none of the rest of the script (including inserting the meta tag) is working. Strange because the Twitter script "widgets.js" is working on my page, but the meta tag does not appear.

like image 982
Mike Eng Avatar asked Mar 09 '11 15:03

Mike Eng


1 Answers

Facebook doesn't use the meta tags in the current page, it requests the page anew and parses it. As that parsing doesn't involve running any Javascript in the page, it won't add the meta tag to the data that is read.

To make the meta tag work it has to be present in the page from start, it can't be added using client script.

like image 79
Guffa Avatar answered Sep 23 '22 18:09

Guffa