Dynamically insert script tag? [duplicate] - javascript

This question already has answers here:
How to append <script></script> in JavaScript? [duplicate]
(6 answers)
Closed 4 years ago.
So i have this script tag
<script async="async" data-cfasync="false" src=""></script>
That I'd like to be able to insert dynamically. I've tried setting it to a variable,
let scriptTag = '<script async="async" data-cfasync="false" src=""></script>';
and adding it using innerHTML to my content div but that doesn't seem to work. I know I'm going about this very wrong and part of me thinks this probably isn't even possible.
The reason I want to do this is so that I can turn ads on and off for testing purposes so my views during testing don't affect the analytics, is this something I should even be worrying about or is it negligible. I just know that I've been banned from chartboost for exactly this without having a testing variable that turned ads on and off.
Edit: Yes this is similar to other questions but those don't address using attributes like 'data-cfasync'. Mandalina and supra28 nailed it on the head.

It seems you are not adding your script tag correctly.
Here is one way you can do it:
const script = document.createElement("script");
script.type = "text/javascript";
script.src = "";
script.async = true;
script.dataset.cfasync = false;
document.body.appendChild(script);
script.addEventListener("load", () => {
console.log("Script added successfully");
resolve();
});

Try this function:
(function () {
if (typeof window.R === 'undefined') {
var s = document.createElement('script');
s.setAttribute('src', 'source goes here!');
document.body.appendChild(s); // this appends the script to the body you can also use document.head.appendChild(s) to append to the head
}
}());

Related

running a script inside index.html with some conditions [duplicate]

This question already has answers here:
Dynamically add script tag with src that may include document.write
(16 answers)
Closed 3 years ago.
We have this script which we want to run only if user agent is ReactSnap. I tried doing this but it does not seem to be working.
<script>
if(navigator.userAgent!=='ReactSnap'){
<script src='//cdnt.netcoresmartech.com/smartechclient.js'</script>
}
</script>
The operator you are using in your conditional statement - !== is checking to see if the condition is not true.
The correct syntax is if(navigator.userAgent=="ReactSnap")
You are also trying to write html in a javascript context.
You should create your script tag using javascript, like the below example:
if(navigator.userAgent=="ReactSnap"){ // check userAgent
var script = document.createElement("script"); // create a script tag
script.setAttribute("type","text/javascript"); // set type to js
script.setAttribute("src", "//cdnt.netcoresmartech.com/smartechclient.js") // define src for script tag
document.head.appendChild(script); // load script into document head, or change this to a specific location
}
This solution waits to add the script element to the page until we know the condition is true (tested in Chrome):
<body>
<div>Page content goes here</div>
<script>
let conditionalScript = document.createElement("script");
conditionalScript.innerHTML = "alert('woo!')";
// (But set .src instead of .innerHTML)
let userAgent = 'ReactSnap';
if(userAgent == 'ReactSnap'){
// (But check `navigator.userAgent` instead of `userAgent`)
document.querySelector("body").appendChild(conditionalScript);
}
</script>
</body>
I'd suggest using createElement, changing the source with setAttribute and appending it to the head like this.
if(navigator.userAgent!=='ReactSnap'){
let smartTech = document.createElement('script');
smartTech.setAttribute('src', '//cdnt.netcoresmartech.com/smartechclient.js');
document.head.appendChild(smartTech);
}
You can try something like this:
<script>
if(navigator.userAgent=='ReactSnap'){
var script = document.createElement('script');
script.src = "//cdnt.netcoresmartech.com/smartechclient.js";
document.head.appendChild(script);
}
</script>

Loading javascript import into React application

Edit
I decided to try adding the script tags to the index.html file and conditionally rendering them.
<script type="text/javascript">
var $show_stuff = 'no';
var $add_stuff = 'yes';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.example.com/includes.php?stuff=true';
document.getElementById('feed').appendChild(script);
</script>
Then in the component I want the feed to show up I did this,
<div id="credit-feed" />
I also tried conditionally rendering the script tag in the index.html file like this,
if(window.location.href === "localhost:3000/my/path" ) { script tag... }
These both do not work as well. The script tag does not show up in the div in the first example and the second does show the script tag but it does not render.
But, when I add the script tag like normal to the head of the HTML file, the feed renders as I would expect.
Background
We do business with a company that provides us a Javascript script tag which appends the data from it's response into the body of our web page. We have had a PHP site for the past 8 years without problems but now that we are switching to React, we can not figure out the correct way to use this tag in the component it will live.
Problem
When we add the script tag to the React component, it does not append the correct data to the page. In fact it does not append any data to the page.
Example
I have tried to load the script tag like normal,
<script type="text/javascript">
var $somevar = "false";
var $addjquery = "yes";
</script>
<script
type="text/javascript" src="https://www.example.com/do/deef.php?feedtype=all ">
</script>
Another way I have tried in the React component,
componentWillMount() {
const script = document.createElement('script');
const $somevar = 'false';
const $addjquery = 'yes';
script.src = 'https://www.example.com/get/feed.php?&data=all';
script.async = true;
document.body.appendChild(script);
}
Question
What is the correct way to load the script tag so it will append the data to my application?
Usually with a React app, you will have an index.html file that contains the React component. You should put the <script> reference inside the html file. So I would definitely use the first approach you mention. If it's not loading, can you check the browser inspector and find out what kind of error you are getting? For one thing, you should remove the empty white space from the URL. That could be the issue.

Javascript (Remote include) : HTML Elements creation on-the-fly? [duplicate]

This question already has answers here:
Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
(4 answers)
Closed 6 years ago.
I'm trying to make a floating HTML button, along with the interaction on it (like: Popping up a form when clicked) by letting the people just EMBED some Javascript inside their Page.
So it's like, my HTML Elements should be generated on top of their page (at different domain) remotely.
For example, i have seen something like Uservoice Feedback Button and Form, it looks like:
We can have that Button generated on our site. The only thing we need to do is to embed their Javascript in our page:
<!-- USERVOICE -->
<script type="text/rocketscript">
var uvOptions = {};
(function() {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/xxxxxxxxxxxxxxxxxxxxx.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>
I tried this
Then in order to achieve similar thing, i tried with my own 2 domains. On my Webpage at www.domain-a.com, i embed:
<script type="text/javascript">
(function() {
var myButtonJS = document.createElement('script'); myButtonJS.type = 'text/javascript'; myButtonJS.setAttribute('defer', 'defer');
myButtonJS.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.domain-b.com/myButton.js?3';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(myButtonJS, s);
})();
</script>
On the www.domain-b.com, inside the myButton.js:
document.write('<div style="z-index:99999999;padding:5px 10px 2px 10px;border:1px solid #000000;position: fixed;bottom: 10px;right: 10px;_position:absolute;_top: expression(offsetParent.scrollTop+document.documentElement.offsetHeight-60);direction:ltr;background:#7fff00;">Click me!</div>');
But when i run, http://www.domain-a.com, the browser says:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
So please kindly let me know:
What are the standard (proper) ways to achieve such ones?
(In other words) how do i properly generate the HTML elements on top of remote sites, when they include the Javascript i provided to them?
Thanks all :)
IMHO, the better way to do it is create the element on the fly from your externa js then load the script in the body of the html, that way you are sure that the document is loaded and then just hook in the body of document e.g:
document.getElementsByTagName('body')[0]
in your external script. then append your element there. :)
You can create A DOM element, use innerHTML to set its contents ant then attach to the DOM when the content is ready:
var myElement = document.createElement('div');
myElement.innerHTML = '<div style="z-index:99999999;padding:5px 10px 2px 10px;border:1px solid #000000;position: fixed;bottom: 10px;right: 10px;_position:absolute;_top: expression(offsetParent.scrollTop+document.documentElement.offsetHeight-60);direction:ltr;background:#7fff00;">Click me!</div>';
document.addEventListener("DOMContentLoaded", function() {
document.body.appendChild(myElement);
});

Inserting a <script> tag dynamically via jQuery

I'm trying to add a widget to the page in run-time. Based on this post, I wrote the code below. Unfortunately, it doesn't show anything. Can anybody tell me why?
<script type="text/javascript">
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// Use any selector
$(".testWidget").append(s);
});
</script>
<div class="testWidget">
</div>
If I put the same script as below, it works and shows some information on the page. However, I should insert the script dynamically, not as static.
<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>
You should be getting this warning in the console, Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Here's a way around that:
<script type="text/javascript">
$(document).ready(function () {
// Save a copy of the document.write method
var oldWrite = document.write;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// After script is loaded, revert document.write to the original
s.onload = function () {
document.write = oldWrite;
};
var $testWidget = $('.testWidget');
// Redefine document.write to make the script's call work
document.write = function (html) {
$testWidget.html(html);
};
$testWidget.append(s);
});
</script>
The script tag you include programatically has to be parsed by the browser. Just by inserting the script tag the included code is not parsed by the JavaScript interpreter.
If you explain what you want to finally achieve I am pretty sure that must be a simpler way to do it.

Executing a javascript that is injected as a script element via bookmarklet?

I am using bookmarklet to inject a element in document with a custom JS script file. I did it like this:
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'http://www.myurl.com/my_js_script.js';
var oldscript = document.getElementsByTagName('script')[0];
oldscript.parentNode.insertBefore(newscript, oldscript);
But I can't figure out how to actually execute it. Can someone tell me how can I execute that JS file?
Note: Since this can be a Greasemonkey script as well, I am tagging this question for Greasemonkey as well.
Script tags are automatically downloaded and executed when they're added to the document. Note, however, that the script you're using may fail if the document you're injecting into doesn't already contain any <script> tags, as oldscript will be undefined.

Categories

Resources