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();
}
}
};
Related
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!.
Good afternoon, I am new to programing and have been having problems making a javascript/jquery API call load to a Twitter Tweet. The goal is to be able to hit the Tweet button and send the current quote featured on the page in a Tweet. This is my current attempt on CodePen with the Javascript below;
var counter = 0;
var $body = $('body'),
redVal = 55,
greenVal = 50,
blueVal = 25,
quote;
var sendText = "something current..."; //this is the variable that should be replaced by the API calls and sent to Twitter
//this is Twitter's function to format the page
window.twttr = (function(d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = {
_e: [],
ready: function(f) {
t._e.push(f)
}
});
}(document, "script", "twitter-wjs"));
//the actions to call the quote API
function start() {
redVal = (redVal + 45) % 255;
greenVal = (greenVal + 40) % 255;
blueVal = (blueVal + 20) % 255;
var colorVal = "rgba(" + redVal + "," + greenVal + "," + blueVal + ", 0.4)";
$body.css({"background-color": colorVal });
if (counter % 2 == 0) {
$.ajax({
url: "http://quotes.stormconsultancy.co.uk/quotes/random.json?",
jsonp: "callback",
dataType: "jsonp",
data: {
q: "id, author, quote",
format: "json"
},
success: function( response ) {
var quote = response.quote;
var author = response.author;
document.getElementById("textDisplay").innerHTML = quote;
document.getElementById("author").innerHTML = author;
passText(quote);
}
});
counter += 1;
} else { $.ajax({
url: "http://api.icndb.com/jokes/random?",
jsonp: "callback",
dataType: "jsonp",
success: function( response ) {
var quote = response.value.joke;
var author = " ";
document.getElementById("textDisplay").innerHTML = quote;
document.getElementById("author").innerHTML = author;
passText(quote);
}
});
counter += 1;
}
}
//my attempted helper function to pass the quote values
function passText(superT) {
console.log(superT);
sendText = superT;
return sendText;
}
//the API call to Twitter to send the Tweet
twttr.ready(function (twttr) {
twttr.events.bind('tweet',
twttr.widgets.createShareButton(
'https://dev.twitter.com/',
document.getElementById('container'),
{
text: sendText }
));
})
I think the issue is that the API calls as conducted in the jQuery AJAX script are not being recognized as a reassignment to the quote variable in a way that is accessible outside of the jQuery AJAX call. I read other suggestions ( example ) to try and assign the quote variable from global scope or pass the value through a helper function ( example, as I attempted above…), but both just send the value initially assigned to the quote variable to the Twitter API without the JQuery values.
I hope there is something simple that I don’t know that will get this working. If it is not an issue with the scope of the variable, or if there is a better way to approach this than the JQuery AJAX function I would appreciate any suggestions. Thank you for your time and any help.
How do i asynchronously load my sdk(JS file) in html and call the methods in it once my SDK object is ready on similar lines like how googles analytic code spinet does or facebook sdk , i have a public object MYSDK and it has some properties and method which i would like to invoke when script is loaded in the html.
Right now im doing something like this
(function (url,callback){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://localhost:8181/init.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
s.onload=function(){
mysdk.init({'userid':'37241d4f-fbd1-48ef-91fd-b359d20c7e31'});
};
})();
I want to implement something like this .
(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', '//www.google-analytics.com
analytics.js', 'ga');
ga('create', 'UA-xxxxxxxx-x', 'xxxxxx.com');
ga('send', 'pageview');
What i tried .
(function(i, s, o, g, r, a, m){
i['my_sdkObjectName'] = 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', 'http://localhost:8181/myt-sdk.js', 'my_sdk');
my_sdk('init', '{"userid":"abcd-1234"}');
what i get ?
my_sdk is not a function.
console.log my_sdk gives
(){
(i[r].q = i[r].q || []).push(arguments)
}
ga is defined inside google js file (www.google-analytics.com/analytics.js)
You have to define mysdk inside your js file.
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);
}
}
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 );
}