Javascript: update a src with dynamic info - javascript

I am trying to dynamically change the src of a tag. It pulls in the src to the tag just fine, but it doesn't run the javascript inside of the "example.js"
My.html
<script src='' id="s1"></script>
<script language="javascript">
function changeSrc()
{
s1.src = "example.js";
};
changeSrc();
</script>
example.js
document.write('<img src="somecoolimage.gif" alt="myweb"/>');
Example.js isn't writing the above info.

You can't change the src of a script block dynamically (it's not consistent across different browsers), add a new script block instead:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'example.js';
document.getElementById('some_div_id').appendChild(script);

Related

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

Conditionally add <script> element into header based on route

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>

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.

Incomplete HTML after Executing `document.write()`

After executing document.write(), Google Chrome shows me that the HTML codes is changed from Code A to Code B. It seems that document.write() overwrite the entire page. If yes, how to append the script tag inside head tag?
Code A : Before Executing document.write()
<!--DOCTYE html-->
<html>
<head>
<script src=".\js\main_CasCode.js"></script>
</head>
<body onload="main()">
<p>hi</p>
</body>
</html>
Code B : After Executing document.write()
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
</html>
JavaScript in File .\js\main_CasCode.js
function main() {
//console.log = function() {};
loadjQuery();
//waitjQueryLoaded_and_start();
}
function loadjQuery() {
console.log("Loading jQuery...");
var s = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>';
document.write(s); //<----Problem Here
}
That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload). It only appears to append when called during the rendering of the page.
A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism.
var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
In other news, why are you loading jQuery dynamically when you have control of the page? Why not add it directly as a <script> on the HTML?
I don't think you want to be using document.write at all. You can use the following. Make a script element, and append it to the head element
var head = document.getElementsByTagName('head')[0]
var s = document.createElement('script')
s.src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
head.appendChild(s)
document.write overwrites the whole DOM
You can create a function
function loadjQuery() {
console.log("Loading jQuery...");
var scrpt = document.createElement('script');
scrpt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
document.head.appendChild(scrpt);
}

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

Categories