How to append multiple scripts in one time? Jquery - javascript

var script = document.createElement('script');
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
script.type='text/javascript';
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
promptForUserEntries();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
This inject one script in the first Head. I have three other scripts and I insert theme by the same way, now I'm looking for how to insert multiple script in a Tag in one time.
Thank you

var scripts = ["/path/to/script.js", "/path/to/script2.js"];
for (index = 0; index < scripts.length; ++index) {
var script = document.createElement('script');
script.src = scripts[index];
script.type='text/javascript';
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
//promptForUserEntries();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
}
This will loop through your array of scripts to append, and append them

Here is a modified solution based on Ole's answer. It allows for both scripts with src tags and script blocks - Useful for loading Google Analytics code after cookie consent, for example.
/**
* Append a block of script code to the head
* Code can contain scripts with src attribute
* and script blocks
*/
function appendScriptBlocks (code) {
let tempEl = document.createElement('div')
tempEl.innerHTML = code
let scripts = tempEl.getElementsByTagName('script')
for (let index = 0; index < scripts.length; ++index) {
var script = document.createElement('script');
script.type= 'text/javascript';
if(scripts[index].src) {
script.src = scripts[index].src;
}
else {
script.innerHTML = scripts[index].innerHTML
eval(scripts[index].innerHTML)
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}

Related

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")
})

Append javascript function to div

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!.

How to hide an element until script animation is applied

how can i show a < script > in html before the page load the content?
<script>
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('uhrzeit').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
the first one just shows the time of day... more important is the second part. At the moment the website is loading the content and shows me the Edge-Animate animation after the content is complete loaded. And you may mention it sucks that the animation comes after paged is loaded...
<!--Adobe Edge Runtime-->
<script>
var custHtmlRoot="hin-aktuell/Assets/";
var script = document.createElement('script');
script.type= "text/javascript";
script.src = custHtmlRoot+"edge_includes/edge.6.0.0.min.js";
var head = document.getElementsByTagName('head')[0], done=false;
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done=true;
var opts ={
scaleToFit: "none",
centerStage: "none",
minW: "0px",
maxW: "undefined",
width: "100%",
height: "100%"
};
opts.htmlRoot =custHtmlRoot;
AdobeEdge.loadComposition('hin-aktuell', 'EDGE-2489594', opts,
{"dom":{}}, {"dom":{}});
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
</script>

How to insert javascript code in iframe tag

I am doing like this but not working:-
I am trying to insert the pixel in iframe and then append it to the body.
jQuery('#subscribr').append('<iframe>
<script language="javascript" src="http://www.abc/static/st.v2.js"></script>
<script language="javascript">
var ef_event_type="transaction";
var ef_transaction_properties = "ev_ProductViews=1";
/*
* Do not modify below this line
*/
var ef_segment = "";
var ef_search_segment = "";
var ef_userid="xxxx";
var ef_pixel_host="pixel.abc.net";
var ef_fb_is_app = 0;
effp();
</script>
</iframe>');
enter code here
Scripts like that appear to break when </script> is included in the string. A workaround to that could be to add the elements through dom manipulation:
iframe = $('<iframe>');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.abc/static/st.v2.js"; // Or:
script.text = "Your code here!"
iframe[0].appendChild(script);
iframe.appendTo('#subscribr'))
This is the solution which worked for me..
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://www.abc/static/st.v2.js";
// Use selector here
jQuery("#subscribr").append(s);
Working sample: http://fiddle.jshell.net/f2x7G/
var doc = null;
if(iframe.contentDocument) doc = iframe.contentDocument;
else if(iframe.contentWindow) doc = iframe.contentWindow.document;
else if(iframe.document) doc = iframe.document;
if(doc == null) throw "Document not initialized";
doc.open();
var script = doc.createElement("script");
script.type = "text/javascript";
// script.src = 'http://www.abc/static/st.v2.js';
script.text = "alert('voila!');"
doc.appendChild(script);
doc.close();

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