Append javascript function to div - javascript

I need to add the following code to the footer of my page, but I have to do it using javascript code.
Code I need to add:
<script type="text/javascript">
(function (d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter39519115 = new Ya.Metrika({
id:39519115,
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
} catch(e) { }
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function () { n.parentNode.insertBefore(s, n); };
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else { f(); }
})(document, window, "yandex_metrika_callbacks");
What I tried to add:
$('#footer').append('<script type="text/javascript">' + (function (d, w,.... + '</script>');
However, this does not work for me.

Place your javascript in a separate .js file and then you need to use the document.createElement method to add/append your script to your footer block.
Try the below snippet.
var scriptSource = document.createElement('script');
var scriptURL = 'your_script_file_url_goes_here';
scriptSource.type = 'text/javascript';
scriptSource.src = scriptURL ;
$("#footer").append(scriptSource);
Hope this helps!.

Related

Multiple versions of html2canvas

I updated version of html2canvas from v0.5.0 to v1.0.0, then a certain function stopped working on iOS.
So, I'd like to use v0.5.0 on iOS and v1.0.0 on other devices.
How can I have and use both versions of html2canvas on my web app?
Try writing custom function.
(function (w, d) {
"use strict";
var h = d.getElementsByTagName("head")[0],
s = d.createElement("script");
w.d3 = null;
s.src ="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0/html2canvas.min.js";
s.onload = function () {
w.d3_3_5_3 = w.d3;
w.d3 = undefined;
s = d.createElement("script");
s.src ="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0/html2canvas.min.js";
s.onload = function () {
w.d3_3_5_4 = w.d3;
w.d3 = undefined;
s = d.createElement("script");
s.src = "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.0.0/html2canvas.min.js";
s.onload = function () {
w.d3_3_5_5 = w.d3;
w.d3 = undefined;
};
h.appendChild(s);
};
h.appendChild(s);
};
h.appendChild(s);
}(window, document));
Hope this helps.!

Run javascript after specific seconds

I'm adding javascript on my website by this code:
<script type="text/javascript" src="https://www.fileoasis.net/contentlockers/load.php?id=6f29997ae5eebe6d78b97e842d1c3835"></script>
Is any solution to make this script will run/load after few seconds after website loaded?
If there is a function in the external library, load it as usual, then in your main page code add:
// When the DOM is built...
window.addEventListener("DOMContentLoaded", function(){
// Run the named function after the specified delay
setTimeout(externalFunctionName, millisecondDelay);
});
If there is not a named function in that external library, then wrap all the code in that library in a named function and use the technique above.
try this out :
<script>
setTimeout(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://www.fileoasis.net/contentlockers/load.php?id=6f29997ae5eebe6d78b97e842d1c3835";
$("head").append(s);
} , 3000);//3 seconds
</script>
Several of the answers show how to load the script using jQuery.
Using plain JavaScript:
<script>
function loadScript() {
console.log('Loading');
var secondsToWait = 3;
setTimeout(function() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://www.fileoasis.net/contentlockers/load.php?id=6f29997ae5eebe6d78b97e842d1c3835";
var head = document.getElementsByTagName("head")[0];
head.appendChild(s);
}, secondsToWait * 1000);
}
window.addEventListener("DOMContentLoaded", loadScript);
</script>
You can verify it loads using the newtwork tab in web developer tools.
Google loads their scripts like this:
<script>
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o), m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
</script>
Which is equivalent to this:
var a=document.createElement("script");
a.async = 1;
a.src = "https://www.google-analytics.com/analytics.js";
var m = document.getElementsByTagName("script")[0];
m.parentNode.insertBefore(a, m); //insert the srcipt before the first script on the page.
Which, given that a majority of web pages have a script tag in their <head> tag is the same as using document.getElementsByTagName("head")[0].appendChild.
jQuery loads scripts using the same method of append the created script element to the head tag:
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};

Make sure these files are loaded before it run any other script

Hi I have a stylesheet and JavaScript function which loads in all the required files for that template.
However I am having a bit of an issue due to when the other script tags run within the template file (plan js code) it does not wait for the required files to load.
So what you have happening is scripts not recognizing functions and other JS functions.
JS Code
<script type="text/javascript">
var uid = '{$smarty.session.ipet_user}';
function stylesheet(url) {
var s = document.createElement('link');
s.rel = 'stylesheet';
s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
function script(url) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
(function () {
script('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
script('https://apis.google.com/js/api:client.js');
script('https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyBk99v0F4qkmvxifqOD48YktK-QO-3kopI');
script('./templates/main/user-theme/javascript/google.js');
script('plugins/getmdlselect/getmdl-select.min.js');
script('./templates/main/user-theme/javascript/facebook.js');
script('./templates/main/user-theme/javascript/newprofile.js');
script('./templates/main/javascript/zipcode.js');
stylesheet('https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css');
stylesheet('https://fonts.googleapis.com/css?family=Roboto');
stylesheet('https://fonts.googleapis.com/icon?family=Material+Icons');
stylesheet('./templates/main/user-theme/tpl-files/material.act.css');
stylesheet('plugins/dropzone/dropzone.css');
stylesheet('plugins/stepper/stepper.min.css');
stylesheet('./templates/main/user-theme/tpl-files/style.css');
stylesheet('./templates/main/style/newprofile.css');
stylesheet('plugins/getmdlselect/getmdl-select.min.css');
})();
</script>
You can use load event of <script> and <link> element, Promise constructor and Promise.all() to return a resolved Promise once all requested resources have loaded by passing an array of URL's to request to Array.prototype.map() where each array of URL's is concatenated to a single array where each function is called which returns a Promise
function stylesheet_(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('link');
s.rel = 'stylesheet';
// s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject;
})
}
function script(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject
})
}
function loadStylesAndScripts(styleList = Array(), scriptList = Array()) {
return Promise.all(
styleList.map(stylesheet_)
.concat(scriptList.map(script))
)
}
let requests = loadStylesAndScripts();
requests.then(function() {
console.log("styles and scripts loaded")
})
.catch(function(err) {
console.log("an error occurred requesting styles and scripts")
})

Fetching image from php web service using JSON in javascript

I want to fetch images from the php web service in my javascript code using json. The alert in the for loop returns "undefined". Please help with your suggestions.
<script>
var menu_category;
var menu_id = [];
var menu_title = [];
var menu_img = [];
"use strict";
function jsonp(url) {
alert("JSONP URL");
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
function jsondata(data) {
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var parsed_data = parsedata["main Category"];
for (var i = 1; i <= parsed_data.length; i++) {
alert("FOR");
menu_id[i] = parsed_data.mcatid;
alert(menu_id[i]);
}
}
jsonp("http://remoteaddress/maincategory.php?callback=jsondata");
</script>

JS get and insert into <script>

I'm writing this code for an extension but It returns:
Origin chrome-extension://gjganecebobheilkbpmhmocibjckgidc is not allowed by Access-Control-Allow-Origin
var randomstring = '';var jsid = 0;
for (var i=0; i<20; i++) {
var rnum = Math.floor(Math.random() * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".length);
randomstring += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".substring(rnum,rnum+1);
}
function addS(file){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", file, false );
xmlHttp.send( null );
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
// s.src = file;
s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
addS('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
addS('http://domain.com/functions.js'');
I would use jQuery but I can't because it breaks the source code of the page, what I want is to do the same as this, but in javascript and skipping that error
function addS(file){
jsid = jsid + 1;
$.get(file, function(data) {
var string = '<script type="text/javascript" async="true" id="'+randomstring+"_unique"+jsid+'" class="'+randomstring+'">'+data+'</script>';
$('head').append(string);
});
Additional Info
I'm gonna insert jquery.js and functions.js with an ID like this tags:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" async="true" id="AWhAXksocT6o6OrBxT28_unique1" class="AWhAXksocT6o6OrBxT28"></script>
<script type="text/javascript" src="http://domain.com/functions.js" async="true" id="AWhAXksocT6o6OrBxT28_unique2" class="AWhAXksocT6o6OrBxT28"></script>
with this code:
function addS(file){
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
s.async = true;
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
I need this ID (via var randomstring) to keep alive, that's the main problem because I will need to delete both after function ends but it returns
functions.js: Uncaught ReferenceError: randomstring is not defined using this code
$(document).ready(function(){
alert("Functions loaded");
//Do some functions....
$("."+randomstring).delete();
});
Thanks!
You can't perform a cross-domain ajax request unless the domain you are requesting from implements CORS.
What you are doing currently IS a cross-domain ajax request. If you instead do as Sirko suggested and request it by making the src of the script element you are appending the url to the ajax request, it will properly make the request.
function addS(file){
//var xmlHttp = null;
//xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", file, false );
//xmlHttp.send( null );
//jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
//s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
What is the purpose of this function? In what context is it used? What does it accomplish?
As far as I can see, you're just pasting the content of a file into the script tag.
So why not pass the file url directly to the src parameter of the script tag instead?
function addS( file ) {
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'src', file ) ;
document.head.appenChild( scriptEl );
}

Categories