Create element from external js-script and insert into html - javascript

I'm trying to create a widget. Something like google-adsense blocks, so I need to call the same script from different places of the page. Is it possible to create an element in external js-script and insert it to the place where I called the script?
I do this:
<div><script type="text/javascript" src="loader.js"></div>
<div><script type="text/javascript" src="loader.js"></div>
Loader.js:
var div = document.createElement('div');
div.setAttribute('class', 'inner-div');
document.body.appendChild(div);
And I have:
<div><script type="text/javascript" src="loader.js"></div>
<div><script type="text/javascript" src="loader.js"></div>
<div class="inner-div"></div>
<div class="inner-div"></div>
But I'd like to get this result:
<div>
<script type="text/javascript" src="loader.js">
<div class="inner-div"></div>
</div>
<div>
<script type="text/javascript" src="loader.js">
<div class="inner-div"></div>
</div>

I think I've found the solution. Find current script tag:
<div>
<script type="text/javascript">
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
loadScript('loader.js', function () {
loader().init({script: script});
});
</script>
</div>
loadScript function:
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
then in loader.js:
init: function(args) {
...
var div = document.createElement('div');
div.setAttribute('class', 'inner-div');
args.script.parentNode.appendChild(div);
...
}

Related

Integrate JQuery with HTML

Problem :
How can I integrate my jQuery code with HTML?
The code is working in Chrome console but I have to integrate it with HTML
How should i call the below jQuery code in HTML?
Code:
$(function () {
$('.ibody tr').each(function (a, b) {
var count=0;
var name = $('.cl', b).text();
if(name.indexOf(".CSV")!==-1 && name.indexOf("TAS")!==-1){
var d= a-9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = `https://www.shipper-ml.com/viewReports.do?
ctrl=reportListForDownload&action=DownloadReport&param=${d}`;
}
});
});
Your Script
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$('.ibody tr').each(function (a, b) {
var count=0;
var name = $('.cl', b).text();
if(name.indexOf(".CSV")!==-1 && name.indexOf("TAS")!==-1){
var d= a-9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport&param="+d;
}
});
});
</script>
and if you wanted to call the function either on a button click you could do like this for example
<!DOCTYPE html>
<html>
<head>
// let us say this is your jquery function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
JQuery is nothing but a javascript helper library. So to use any library, first you need to tell HTML that you are writing some functions from that library.
To do that , we need to include the library before you write any code that uses that library. In your case Jquery.
So 1st add the library using
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Then you can use any functions from that library.. in the same HTML file or in a different js file.
To use it in the same HTML file, write your code in the tags.
<script>
$(function () {
$('.ibody tr').each(function (a, b) {
var count=0;
var name = $('.cl', b).text();
if(name.indexOf(".CSV")!==-1 && name.indexOf("TAS")!==-1){
var d= a-9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport&param="+d;
}
});
});
</script>
To use it in a different file,
add your code in a new file (mycode.js), and use the relative path to it in the html file
<script src="mycode.js"/>

Placing Amazon Banner | Angular V4

I'm placing an Amazon banner inside an angular material 2 card.But the problem is that it is not rendering.It shows empty div.What could be the reason.Below is the code showing how I did it.
<md-card class="full-width full-height border-box ">
<div class="adv">
<script type="text/javascript" language="javascript">
var aax_size = '728x90';
var aax_pubname = 'XXXXXXXXXXX';
var aax_src = '302';
</script>
<script type="text/javascript" language="javascript" src="http://c.amazon-adsystem.com/aax2/assoc.js"></script>
</div>
</md-card>
I also tried to to bind it using property binding
<span [innerHTML]="advertisement()"></span>
advertisement(){
return `<div class="adv">
<script type="text/javascript" language="javascript">
var aax_size = '728x90';
var aax_pubname = 'XXXXXXXXXXX';
var aax_src = '302';
</script>
<script type="text/javascript" language="javascript" src="http://c.amazon-adsystem.com/aax2/assoc.js"></script>
</div>`;
}
I also tried to dynamically add the div inside my card,it shows inside the div but the banner doesn't appear.Below is the code showing how I did that.
ngAfterViewInit() {
let x: HTMLElement = document.getElementById('adv');
let s: HTMLScriptElement = document.createElement('script');
s.type = 'text/javascript';
// s.language = 'javascript';
let code = `var aax_size = '728x90';
var aax_pubname = 'XXXXXXX';
var aax_src = '302';`;
let src = document.createElement('script');
src.type = 'text/javascript';
// src.language = 'javascript';
src.src = 'http://c.amazon-adsystem.com/aax2/assoc.js';
try {
s.appendChild(document.createTextNode(code));
x.appendChild(s);
x.appendChild(src);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
console.log(x);
}
After scrapping every post in SO regarding or similar to this question I did not find any solution to this.I followed almost everything in those posts but nothing was working for me.After that I came across postscribe library which does the externally loading of any third party script.
First I installed the library and imported it in my component
import * as postscribe from 'postscribe';
After that all I did was calling a function inside my ngAfterViewInit function, by targetting the div with its id which in my case was adv and passed the script as a second parameter to this function.
ngAfterViewInit() {
postscribe('#adv', `<script type="text/javascript" language="javascript">
var aax_size='728x90';
var aax_pubname = 'XXXXXXXX';
var aax_src='302';
</script>
<script type="text/javascript" language="javascript" src="http://c.amazon-adsystem.com/aax2/assoc.js"></script>`);}
By doing this my banner was loaded.

window.onload not Firing in Embedded html Document

I'm trying to embedd two html documents in another using javascript. The problem I am having is that the onload event does not fire on the embedded document.
paper.htm has several div tags and should contain curve.htm but in curve.htm the onload event is not firing
paper.htm
<html>
<head>
<title>Curve</title>
<script>
(function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'curve.htm', true);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('chartBlock').innerHTML = this.responseText;
}
xhr.send();
})();
</script>
</head>
<body>
<div id="paper">
<div id="border">
<div id="chartBlock"></div>
<div id="titleBlock"></div>
</div>
</div>
</body>
</html>
curve.htm (partial)
<html>
<head>
<script src="File:///Temp/curveData.js" type="text/javascript"></script>
<script>
window.onload = init; //this never fires!
function init() { //... }
</script>
<body>
<canvas id="chartCanvas" width="954" height="625"></canvas>
</body>
</html>
I have tried:
Using jquery to load the html document (many examples here on SO).
Putting onload in the body tag of the html document (curve.htm)
tried with jquery:
<script>
$(function () {
$("#chartBlock").load("curve.htm");
$("#titleBlock").load("titleblock.htm");
});
</script>
tried with html:
<body onload="init()">
Any other ideas to look into would be very much appreciated. Thanks
Because the document will not be loaded...
What you are doing could be achieved with iframes. With an iframe, you are loading a full html document, which will be parsed as such. With the $.load function, you will just bluntly insert html, which will be parsed as <body>'s children. Meaning; the <head>, <meta> tags etc. will be ignored by all/proper browsers, because they should only occur inside the head of a document. Simplified, your output would be:
<html>
<head>
<!-- whatever -->
</head>
<body>
<div id="chartBlock">
<html>
<!-- What?! Another html tag?! -->
</html>
</div>
<div id="titleBlock">
<html>
<!-- And another one... -->
</html>
</div>
</body>
</html>
So, what you want to do, is loading only the contents, what would be inside the <body> tag, and use the success callback of the $.load function to do whatever you want to do if the contents are inserted in your document.
You could still load the page without using iframes, you just need to go about it a little differently. Basically since you're putting an html page inside of a div, the scripts on that page never get rendered.
To make it work, the scripts need to be inserted into the parent documents head.
Get scripts and insert them into head:
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
data;
script.type = 'text/javascript';
...
data = document.getElementById('chartBlock')
.getElementsByTagName('script').item(0).innerHTML;
try {
script.appendChild(document.createTextNode(data));
} catch(e) {
script.text = data;
}
head.insertBefore(script, head.firstChild);
head.removeChild(script);
Retrigger Load Event
var event = new Event('load');
//place after script has been inserted into head
window.dispatchEvent(event);
Using your example above:
curve.htm
<html>
<head>
<script src="File:///Temp/curveData.js"></script>
<script>
window.onload = init; //this will now fire
function init() { alert('loaded'); }
</script>
</head>
<body>
<canvas id="chartCanvas" width="954" height="625"></canvas>
</body>
</html>
paper.htm
<html>
<head>
<title>Curve</title>
<script>
(function () {
var xhr = new XMLHttpRequest(),
event = new Event('load'),
//since the onload event will have already been triggered
//by the parent page we need to recreate it.
//using a custom event would be best.
head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
data;
script.type = 'text/javascript';
xhr.open('GET', 'curve.htm', true);
xhr.onreadystatechange = function (){
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('chartBlock').innerHTML = this.responseText;
data = document.getElementById('chartBlock')
.getElementsByTagName('script').item(0).innerHTML;
//we're extracting the script containing the
//onload handlers from curve.htm,
//note that this will only cover the first script section..
try {
// doesn't work on ie
script.appendChild(document.createTextNode(data));
} catch(e) {
script.text = data;
}
head.insertBefore(script, head.firstChild);
head.removeChild(script);
window.dispatchEvent(event);
//once the scripts have been rendered,
//we can trigger the onload event
}
xhr.send();
})();
</script>
</head>
<body>
<div id="paper">
<div id="border">
<div id="chartBlock"></div>
<div id="titleBlock"></div>
</div>
</div>
</body>
</html>

Call Javascript from inside Javascript

Currently I am using three external JS file.
<script src="https://code.jquery.com/jquery-2.0.0.min.js" type="text/javascript"></script>
<script src="http://example.com/jquery.cookie.js" type="text/javascript"></script>
<script src="http://example.com/js.cookie.js" type="text/javascript"></script>
I like to make all three JS file in one.
Do it possible. i create aio.js and inside aio.js
src="https://code.jquery.com/jquery-2.0.0.min.js";
src="http://example.com/jquery.cookie.js";
src="http://example.com/js.cookie.js";
And then i will add
<script src="http://example.com/aio.js" type="text/javascript"></script>
So the Single File aio.js call all the 3 files.
Thanks in advance.
Here is the Live example..
var element1 = document.createElement("script");
element1.src = "https://code.jquery.com/jquery-2.0.0.min.js";
document.body.appendChild(element1);
console.log(element1)
For you :
Put this code in your http://example.com/aio.js file
window.onload = function() {
var element1 = document.createElement("script");
element1.src = "https://code.jquery.com/jquery-2.0.0.min.js";
document.body.appendChild(element1);
var element2 = document.createElement("script");
element2.src = "http://example.com/jquery.cookie.js";
document.body.appendChild(element2);
var element3 = document.createElement("script");
element3.src = "http://example.com/js.cookie.js";
document.body.appendChild(element3);
}
And in your html file..
<script src="http://example.com/aio.js" type="text/javascript"></script>

insert dynamically string containing script into HTML and executing it dynamically

I have a variable of the form :
var x = '<script type="text/javascript" language="javascript"> ..lots of stuff...</script>
<script type="text/javascript" language="javascript"> ..even more of stuff...</script>'
and I want to insert it with jquery into my HTML code and execute it.
I tried using the append, html and eval without any luck.
Any ideas?
sample script:
<script type="text/javascript" language="javascript">
var clk = 'http://......';
</script>
<script type="text/javascript" language="javascript" src="http://...."></script>
<noscript>
<img src="http://..." width="120" height="600" border="0" alt="">
</noscript>
this will in the end show an img, which will load asynchronously.
Usually having </script> tags nested within other <script></script> tags will break things. You'll need to split them up like in the Javascript below to not cause browser issues.
Here is a working fiddle:
https://jsfiddle.net/2vrfxrse/
Javascript
var jsCode = '<scr' + 'ipt>var executeTest = function(){ alert("This is a test."); }</scr' + 'ipt>';
$('head').append(jsCode);
HTML
<script>executeTest();</script>
This solution will probably work for your specific scenario:
var rx = new RegExp("<script .*?>(.*?)<\/script>", 'g');
var x = '<script type="text/javascript" language="javascript">alert("..lots of stuff...");</script><script type="text/javascript" language="javascript">alert("..even more of stuff...");</script>';
var res = rx.exec(x);
while (res) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(res[1]));
document.body.appendChild(s);
res = rx.exec(x);
}
JSBin: http://jsbin.com/menocumiya/edit?html,js,console,output
You can use Jquery getScript:
//Moment example
if (typeof moment == "undefined") {
var url = "~/assets/js/moment.js";
$.getScript(url);
}
Or Jquery Function:
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
$(function(){
var test = "this.Foo = function() {alert('hi');}";
var F=new Function (test);
(new F()).Foo(); //Shows "Hi" alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Categories