I know how to insert standard script to body with javascript.
Actually I'm using this:
document.body.appendChild(document.createElement('script')).src = 'https://url.com';
But I have found a script that looks different and i'm not very sure how I shall proceed:
<script type="text/javascript"> var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; </script> <script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
How I can insert this script into the body using javascript? As it contains vars
This is how google use to append scripts dynamically.
Please Note the async property marked as true so you won't need to worry about the sequence of the resource loading (dom parsing that might halt the DOM tree creation)
When async is marked as true, the script will be downloaded and executed as soon as possible (after the script has been downloaded) and HTML page will be parsing simultaneously.
When async is marked as false, the process of script downloading and execution will be carried out before starting of any HTML page parsing hence HTML parsing will halt while script is downloaded (which is not good for performence)
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://url.com';
var element = document.getElementsByTagName('script')[0];
element.parentNode.insertBefore(script, element);
})();
You can create a TextNode element and append it to the script to match your case. For example:
var inlineCode = document.createTextNode('alert("hello world")');
script.appendChild(inlineCode);