How to dynamically add scripts to new webpages in javascript? - javascript

I'm currently learning javascript without any frameworks. How do you guys redirect to another html file, then assign a script to it dynamically?
So far, what I have done is:
onClick()
{
window.location = newpage.html;
var script = createElement('script');
script.src = dynamic + 'script.js';
var body = document.findbyID('body');
body.appendChild(src);
}
One of the examples of the dynamic script goes like this:
function addText()
{
var text = createElement('p');
text.innerhtml = sometext;
var textHolder = findbyid('div_somewhere_in_html');
body.appendChild(text);
}
The above code doesn't show the text inside the new webpage. The window.location command works. But after dynamically adding a text, it will not show up inside the new webpage. If I would console.log(window.location), it would only show my localhost:3000.
EDIT:
All files are hosted locally.

Since you own the target page, you can load (instead of pushing) a script based on a query string parameter. For example:
newpage.html
<!DOCTYPE html>
<html>
<body>
<script>
const dynamic = new URL(location).searchParams.get('script-prefix');
const script = document.createElement('script');
script.src = dynamic + 'script.js';
document.body.appendChild(script);
</script>
</body>
</html>
anotherpage.html
When clicking the following link, newpage.html will load and execute a script called MyPrefixscript.js.
<html>
<body>
My Link
</body>
</html>
BTW, I used an anchor, but window.location = '/newpage.html?script-prefix=MyPrefix' would work as well.

Related

Adding script tag in react component not working?

My requirement is to add two script tags to my react component where the variables used in first script is referenced in second script.
<script type="text/javascript" language="javascript">
var aax_size='300x250';
var aax_pubname = XXXXXXXX;
var aax_src=XXXXXX;
</script>
<script type="text/javascript" language="javascript" src="http://c.amazon-adsystem.com/aax2/assoc.js"></script>
Including the first script in index.html and including the second script in component enables the iframe to work properly. But using it in multiple components with different values is not working as the first script is in the index.html
Added the script in component using this way: https://stackoverflow.com/a/34425083/3991377
Something like this
const script = document.createElement("script");
document.body.appendChild(script);
script.innerHTML = "var aax_size='300x250'; var aax_pubname = XXXXXXXX; var aax_src=XXXXXX;"

Jquery Script not loading in head when I create dynamically html page using javascript

I created dynamically new window in JavaScript and add some HTML code in it through JavaScript, but when I insert some script link into html head, it does not load when window is open.
<script type="text/javascript">
function newWindowMap(){
var myWindow = window.open('','_blank');
var head = myWindow.document.getElementsByTagName('head')[0];
var body = myWindow.document.getElementsByTagName('body')[0];
var jqueryScript = myWindow.document.createElement('script');
jqueryScript.src = 'jquery.min.js';
jqueryScript.type = "text/javascript";
head.appendChild(jqueryScript);
var alertScr = myWindow.document.createElement('script');
var inlineScript =
document.createTextNode('$(document).ready(function(){alert("Hello World!");});');
alertScr.appendChild(inlineScript);
body.appendChild(alertScr);
}
</script>
Error on console:
Uncaught ReferenceError: $ is not defined
at :1:1
$ is from JQuery, which is a popular library for JavaScript, and from the looks, you haven't imported it.
Add this into your head tag to fix the issue
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Install Customer.io Tracking Script in Yii

I am trying to install Customer.io to Yii but not sure the process so asking if anyone knows, how should I use the JavaScript code from http://customer.io/docs/api/javascript.html?
I tried to copy into my footer.php under views for main module but it gives me errors.
The simplest way to include JS tracking code in all pages of your site, is to insert it into the master layout.
Browse to protected/views/layouts/main.php, and insert the JS at the bottom of your page right before the closing <body> tag like this:
<script type="text/javascript">
var _cio = _cio || [];
(function() {
var a,b,c;a=function(f){return function(){_cio.push([f].
concat(Array.prototype.slice.call(arguments,0)))}};b=["identify",
"track"];for(c=0;c<b.length;c++){_cio[b[c]]=a(b[c])};
var t = document.createElement('script'),
s = document.getElementsByTagName('script')[0];
t.async = true;
t.id = 'cio-tracker';
t.setAttribute('data-site-id', 'YOUR SITE ID HERE');
t.src = 'https://assets.customer.io/assets/track.js';
s.parentNode.insertBefore(t, s);
})();
</script>
</body>
</html>

Manipulating html page by .js file

I have successfully called the following JavaScript code to populate an image and description using parameters.
The image and description are in tags and are called imagePlaceHolder and descriptionPlaceHolder. As I say, this works perfectly.
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
PlaceHolder.innerHTML=descriptiveText;
}
What I now require is to place the javascript in its own file and call it from the HTML page using <script src="xxxx.js"></script>
The problem is that the object in the <div> is not recognized. I need to amend the line
document.getElementById('imagePlaceHolder');
to point to the HTML file containing object to manipulate.
Can anyone advise me of the correct syntax please?
In the HTML file you need to link the javascript file in the header
E.g.
<head>
<script src="/scripts/yourjavascript.js" type="text/javascript"></script>
</head>
then do a onload function at the top of your javascript file
window.onload = function(){
changeImage("imgName", "descriptiveText");
}
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
text.innerHTML=descriptiveText;
}
any javascript using document should reference the html document

Insert code snippet to div

I used Jquery to insert a variable to div. Please check my code.
var msg = '<script src="https://gist.github.com/3010234.js?file=new.html.erb"></script>'
$('.result').html(msg);
msg variable contains a script that render a code snippet. msg is dynamic variable.
The above code is not working to insert code snippet to div.
Any Idea?
This script generate code snippet like this.
To add script, I would add it to head like this;
var s = document.createElement('script');
s.src = 'https://gist.github.com/3010234.js?file=new.html.erb';
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
You cannot load a github gist into a page dynamically using that embed code. The embed code is fine if you can add the script tag to the HTML, but to do it dynamically via JavaScript as you are trying to do, it won't work because it relies on document.write().
Instead, use the github gists api:
$.get("https://api.github.com/gists/3010234", function(response) {
$(".result").text(response.data.files["new.html.erb"].content);
}, "jsonp");
Working demo: http://jsfiddle.net/naTqe/
function loadScript() {
var script = document.createElement("script");
script.src = "https://gist.github.com/3010234.js?file=new.html.erb";
script.type = "text/javascript";
document.getElementById("result").appendChild(script);
}
It looks like your remote JS is buggy. I ran it through JS Lint and came up with several errors.
Anyway, here is my working example. Keep a javascript console open and you'll see the error when it tries to parse the remote JS.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Jquery test</title>
</head>
<body>
<h1>jQuery</h1>
<p class="result">Some result</p>
<script>
/*<![CDATA[*/
$(document).ready(function(){
var msg = '<script type="text/javascript" src="http://gist.github.com/3010234.js?file=new.html.erb"><\/script>";
$('.result').html(msg);
});
/*]]>*/
</script>
</body>
</html>

Categories

Resources