Using Google Optimize I want to run an A/B test which includes loading an external script for one of the variants. In order to do this, I need to be able to add my script before the closing <body>
tag, preferably.
<script type="text/javascript" src="https://example.com.js" async></script>
</body>
If I select the body tag using the visual editor, I do not have the option to Edit HTML. You can Insert HTML, but if I try to append the script tag, Google tells me I have to remove it.
Is there a way to do this?
You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
That's because SCRIPT TAG is not a VOID ELEMENT. In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!
The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
you might try adding following snippet instead of inserting the script directly in HTML block:
<script>
var script = document.createElement('script');
script.onload = function () {
//do stuff with the script
};
script.src = "https://example.com.js";
document.body.appendChild(script);
<\script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With