How to add html to <head> using jQuery

I am trying to add an open Facebook graphic tag to an open HTML tag (based on dynamically generated content on the page).

$(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 in itself is working fine. js violin

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>'); }); 

he scores shaky. js fiddle In the js fiddle, some special characters are inserted into the body, and none of the rest of the script (including the insertion of the meta tag) works. Strange, because the Twitter script "widgets.js" works on my page, but the meta tag does not appear.

+4
source share
1 answer

Facebook does not use meta tags on the current page, it requests the page again and analyzes it. Since this parsing is not related to running any kind of Javascript on the page, it will not add a meta tag to the data being read.

To do work on meta tags, it must be present on the page from the beginning, it cannot be added using the script client.

+7
source

Source: https://habr.com/ru/post/1343028/


All Articles