use javascript to write a random <script>

给你一囗甜甜゛ 提交于 2021-02-11 13:35:32

问题


How do I add a random 1 of 4 pre-defined <script>s to a webpage?

i.e. A 3rd party tool has 4 e-book download modal forms that are generated by a unique <script> (1 for each e-book).

I want to randomly add 1 of these <script>s to the page, so that on each page load, a different e-book download modal form is displayed.

How would I do this?

I've tried:

var min=1; 
var max=4;  
var random = Math.random() * (+max - +min) + +min; 

switch ($random) {
   case 1:
       document.write(<script src=""></script>)
   break;

but the </script> in the document.write closes the main <script>. Do I need to use HTML ascii code for the < & >?

Help appreciated.

Update:

The scripts I need added are in the format:

<script type='text/javascript' async='true' src='https://app.ontraport.com/js/ontraport/opt_assets/drivers/opf.js' data-opf-uid='p2c187780f17' data-opf-params='borderColor=#ec0c8d&borderSize=5px&formHeight=572&formWidth=60%&maxTriggers=2&onExitIntent=true&popPosition=mc&timeframe=1&instance=1067093054'></script>

回答1:


You can just make a random selection of predefined script src URLs, and then dynamically add the script tag for it:

// List of possible attributes that script element could get
var scripts = [
    { src: "http://abc/scr1.js", "data-opf-uid": "23", "data-opf-params": "y='a'" },
    { src: "http://abs/scr2.js", "data-opf-uid": "81", "data-opf-params": "x=9" }
];
// Select a random entry from above list
var selected = scripts[Math.floor(Math.random()*scripts.length)];
selected.type='text/javascript';
// Create the script DOM element
var script = document.createElement('script');
// Assign the selected properties to the element as attributes
for (var prop in selected) {
    script.setAttribute(prop, selected[prop]);
}
// Add the element to the document
document.head.appendChild(script);

Put this as a script in the body part of your document.

If the remote script is designed to be loaded in the body tag, then the last line should be changed to:

document.body.appendChild(script);

The properties you define in the above scripts object do not need any HTML escaping: that is taken care of when those properties are added to the generated script element using setAttribute(). You mention that your script needs the async attribute, but that is irrelevant for scripts that are added via code: they are anyway async. So no need (but also no harm) to add those.



来源:https://stackoverflow.com/questions/55215396/use-javascript-to-write-a-random-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!