Conditionally add <script> element into header based on route - javascript

I have a website with different routes, say site.com/foo and site.com/bar. I would like some widget scripts to be added to the html headers of the site only if the route is site.com/foo (and not if it is site.com/bar)
Currently what I have are a bunch of elements in the header like this:
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","xyz");</script>
so every child route of site.com gets the scripts.
Is there a way to conditionally add in these scripts based on routes using JS and HTML?

Are you somewhat looking for this? It's in plain javascript without any library
<html>
<body onload="onloadFunc()">
</body>
<script>
var script = document.createElement("script");
script.type = "text/javascript";
function onloadFunc() {
let path = window.location.pathname
if(path.search("bar") >= 0){
script.src = "a.js";
} else{
script.src = "b.js";
}
}
document.body.appendChild(script);
</script>
</html>

Related

Add third party script tags (<script>) to react application

I'm creating a component to be included in a big React project, this component loads a group of script tags that looks like
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = XXXX;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//googleads.g.doubleclick.net/pagead/viewthroughconversion/XXXX/?value=0;guid=ON;script=0"/>
</div>
</noscript>
I can't change the contents of this script in anyway, so now I'm using dangerously-set-html-content npm package to add & execute those scripts successfully, but then I get the following console warning:
conversion.js:29 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.
Of course I wish I could tell google to remove that from the code... but, sadly they won't do it, so I would like to know how to be able to load this kind of scripts and make them work.
I tried changing <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js" async></script> as other people suggested but the warning continues.
You can use react-helmet to push the tag from your component.
You can import any script to your react project like this:
loadScript = () => {
const script = document.createElement("script");
script.src = "https://yourlink.js";
script.async = true;
document.body.appendChild(script);
}
and call this function inside useEffect or componentDidMount method

How do I trigger ad on button click? [duplicate]

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

Loading Dropbox dropin.js script in Meteor

I need to load this script in a Meteor project:
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="my-api-key"></script>
I first tried to do a $('head').append('<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="my-api-key"></script>') on Template.Image.onRendered, but the problem is that the library loads every time the template is rendered, and gives this error: dropins.js included more than once
I've also looked at the wait-on-lib package, https://github.com/DerMambo/wait-on-lib, but I'm not able to pass the data-app-key or id to the Router waiton function.
Do you have any suggestions on how to load this script?
I've never used dropbox sdk, but maybe this help you or give some idea for that.
if(window.Dropbox){
// Nice, is already loaded
}
else {
$("head")
.append('<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="your-api-key"></script>');
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.dropbox.com/static/api/2/dropins.js';
head.appendChild(script);
script.onload = function(){
//whatever, I Want It All!
};
}
You can add this on your Template.template_name.onCreated code block.

How to load an external Javascript file during an "onclick" event?

I have 2 divs in my HTML.
<div id="div1"></div>
<div id="div2"></div>
On clicking the "div2" I want to load an external javascript file say for example "https://abcapis.com/sample.js".
I tried including the JS file on onclick event like below,
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://abcapis.com/sample.js";
document.getElementsByTagName("head")[0].appendChild(script);
This included the script tag in the head section but did not load since the script tag will be loaded on page load only (correct me here if I'm wrong).
Is there any other way that I could proceed?
Thanks in Advance.
Using jQuery's $.getScript() function should do the job for you.
Here is a slice of sample code:
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
If you are not using jQuery, you're going to have to learn how to use AJAX to dynamically load new script into your page.
Your code almost works. You need to use .setAttribute. Here is my working code. I used jQuery as my script:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'jquery.min.js');
document.head.appendChild(script);
And that'll do it.
EDIT:
Some more info. When you do something like script.type = 'text/javascript' you are setting a property on the object but this is not necessarily the same thing as associating that property with an actual node attribute.
Are you using jQuery? If so, you can try $.getScript().
You might also want to check this answer. But basically, you can do something like this:
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
$("button").click(function(){
$.getScript("demo_ajax_script.js");
});
An info I missed was, that the path has to be absolute.
Copy and paste this function on your code.
<script type="text/javascript">
getScript=(url)=>{
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
if(document.body == null){
document.head.appendChild(script);
}else{
document.body.appendChild(script);
}
}
</script>
And now call this function with your .js file url.
Example:getScript('https://abcapis.com/sample.js');
Info:
File should not contain DOMContentLoaded or $(document).ready() function

Replace script URL though the console

i'm trying to update my TinyMCE script URL front the frontend without any kind of ftp access using some kind of injection script.
Currently my page loads this in the head:
<script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
My question is how can I update the src URL and then have it loaded into the page all through the DOM console?
You can add Id Attribute In script tag and use Dom,
<script id="tiny" type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script>
function changeSrc(){
var tinytag = document.getElementById("tiny");
tinytag.setAttribute("src", "js/tiny_mce/tiny_mce.js");
}
</script>
You can create script tag using javascript in console using the following code:
var js = document.createElement('script');
js.async = true;
js.src = "js/tiny_mce/tiny_mce.js";
document.body.appendChild(js);
and if you want to update it you already have it's reference so you can update it using
js.src = "somethingelse.js";
Hope that helps....

Categories