I want to execute a script tag <script> as soon as the website load.
I tried a lot of codes but it doesn't satisfy me.
For this, you can add tag after loading page:
<script>
window.onload = function(){
var script = document.createElement('script');
script.async = "true";
script.src = "http://my-site.com/script.js";
let scriptElement = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(script, scriptElement);
}
</script>
Or you can use defer. It will be run after load page:
<script src="myLoadPage.js" defer></script>
Related
I am trying to load some scripts after DOMContentLoaded event and I am trying to use the following script for this. I'm not sure if the following is the best way to do this but I am having an issue with the following code because I need to load jquery first because my other scripts are depend on it. I have no idea how to do this any help would be greatly appreciated. Thank you very much.
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
document.getElementsByTagName('body')[0].appendChild(script2);
});
</script>
Please know that dynamic scripts behave as async by default, which means that the script that loads first will also run first. So, the issue might be here that myscript1.js & myscript2.js are very small scripts and thus it loads and runs first before jquery script could load. To fix this you can pass script.async=false to each script so that script loads and run in the order they are being added to the document like:
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script2);
});
and if you want to keep things DRY (Don't repeat yourself), you can use a helper function like:
document.addEventListener('DOMContentLoaded', function() {
function loadScript(src) {
let script = document.createElement('script');
script.src = src;
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
}
loadScript('https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js');
loadScript('/myscript1.js');
loadScript('/myscript2.js');
});
I've implemented this answer in order to solve my problem but I still can't get the onload event fire.
I need a javascript solution, and I'm trying this on chrome. I know that I need to check for readystate for IE.
What am I missing here?
<script>
var script = document.createElement('script');
script.type = "type/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function(){
console.info("After loading");
mdp.video.loadAllPlayers(".videoPlaceholder");
};
script.src = "/source.min.js";
</script>
Something like that
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="application/javascript">
var el = document.createElement('script');
el.src = "//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js"; // use what ever js file you want but valid one
el.onload = function(script) {
console.log(script + ' loaded!');
};
document.body.append(el);
</script>
</body>
</html>
This script (for Greasemonkey) doesn't work intendedly.
I want to insert an script, and after the script loaded, replace text "Download" to Japanese word (I will use "TEST" instead.).
(function() {
if ((document.URL.match("www.youtube.com/watch?"))||(document.URL.match("c.youtube.com/videoplayback?"))) {
var head = document.getElementsByTagName('head')[0]; //Working
var script = document.createElement('script'); //Working
script.type = 'text/javascript'; //Working
script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
head.appendChild(script); //Working
};})();
What is the problem?
You have to make sure that the elements are already loaded.
Which means, after body content is loaded you can query elements in the body.
This leads to the following solution.
on the BODY tag you have to add the following
<body onload="myOnloadFunc()">
then you have to create the myOnloadFunc as follows:
<script type="text/javascript>
function myOnloadFunc () {
// in here you should place the original code you have created.
if ((document.URL.match("www.youtube.com/watch?"))|| (document.URL.match("c.youtube.com/videoplayback?"))) {
var head = document.getElementsByTagName('head')[0]; //Working
var script = document.createElement('script'); //Working
script.type = 'text/javascript'; //Working
script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
head.appendChild(script); //Working
}
</script>
I am trying to use GoogleMaps.InfoBox on my project, but before load this script, the GoogleMaps API has to be loaded.
Right now I have this code to load everything:
/**
* Load scripts asynchronously
*/
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=-MY-KEY-&sensor=true&callback=initialize";
document.body.appendChild(script);
var scriptInfoBox = document.createElement("script");
scriptInfoBox.type = "text/javascript";
scriptInfoBox.src = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js";
document.body.appendChild(scriptInfoBox);
}
But not always the GoogleMaps API is loaded before than GoogleMaps.InfoBox one.
How can I load JS sorted, waiting for complete the previous one?
You can use the load event of the scripts:
function loadScript(callback) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=-MY-KEY-&sensor=true&callback=initialize";
document.body.appendChild(script);
script.onload = function() {
var scriptInfoBox = document.createElement("script");
scriptInfoBox.type = "text/javascript";
scriptInfoBox.src = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js";
document.body.appendChild(scriptInfoBox);
scriptInfoBox.onload = callback;
};
}
However, you will need to adapt the code a bit to make it crossbrowser-safe like this.
Just use regular script tags right before </body>.
<script src="http://maps.googleapis.com/maps/api/js?key=-MY-KEY-&sensor=true&callback=initialize"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js"></script>
By default, browsers will execute scripts in the order they appear.
So if I have the following:
<script type="text/javascript" src="offsite file I am referencing"></script>
and I simply want to delay the execution of calling that file using settimeout, how would I go about that?
Very strange in that I would have no problem using settimeout on a simple function, but I am kind of stumped in this seemingly more simple situation.
My thought would be I could just make a function that calls that file after x amount of time, but calling the file in the function seems to be escaping me.
you are almost there.
in your settimeout callback function do the following:
var script = document.createElement('script');
script.src = "http://whatever.com/the/script.js";
document.getElementsByTagName('head')[0].appendChild(script);
The simplest way would be to let the script file load normally and just call a main function in it with setTimeout() like this:
<script type="text/javascript" src="offsite file I am referencing"></script>
<script type="text/javascript">
setTimeout(executeMainFunction, 5000); // function in offsite js file
</script>
If you cannot do that for some reason, then you can delay the loading of the external script file like this:
setTimeout(function() {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);
}, 5000);
Here's a reference article on dynamic loading of script files (and other types of resources): http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS.
You can use DOM manipulation to create a new script tag at runtime. Adding it into the document will load the external JS file just as if you had written it into the HTML in the first place.
var loadScript = function(sourceSrc){
var scriptTag = document.createElement('script');
scriptTag.src = scriptSrc;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
You can delay the script from loading, until the page finishes loading, using the HTML script defer attribute:
<script src="offsite file I am referencing" defer></script>
If the purpose of this exercise is to delay the loading of external resources to simulate potential real life scenarios (e.g. when loading 3rd party widgets, etc), then I'd go down a very different route.
The following are two different delay proxy implementations that can be used to simulate and test unexpected network conditions:
http://www.deelay.me/
https://www.npmjs.com/package/grunt-connect-delay
They both work by using a prefix like /delay/5000/ to specify the delay simulation period.
Mozilla Developer Network explains various approaches:
MDN Async Script Techniques
<script async src="file.js"></script>
or
var script = document.createElement('script');
script.src = "file.js";
document.body.appendChild(script);
or if your JavaScript is in a String:
var blob = new Blob([codeString]);
var script = document.createElement('script');
var url = URL.createObjectURL(blob);
script.onload = script.onerror = function() { URL.revokeObjectURL(url); };
script.src = url;
document.body.appendChild(script);
There is also good information when async is not async as well as how to get around those cases.
I have created for ReactJS and its worked for me.
1. File: widget.js with promise:
const delayTime = 20000; // loading 20sec delay.
const loadJS = async () => {
return await new Promise(function (resolve, reject) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://yoururl.com/js/widget.js';
script.onload = resolve;
script.onerror = () => {
reject('Cannot load js')
document.head.removeChild(script);
}
document.head.appendChild(script);
}) }
function initLoadJS() {
loadJS()
.then(()=> console.log('testing'))
.catch((error)=>console.error(error)) }
function delayLoadingJS() {
setTimeout((event)=>initLoadJS(event), delayTime);
}
export default delayLoadingJS;
2. Calling delayLoadingJS() function on the page:
When page loading completed then after 20 sec later initLoadJS() method will trigger and it attach the 3rd party javascript file(https://yoururl.com/js/widget.js) on page.
componentDidUpdate(prevProps, prevState) {
if (this.state.page !== prevState.page) {
delayLoadingJS();
}
}
For a NextJS cript, the code below will work fine:
<script id="sample_id">
setTimeout(function(){
var script = document.createElement('script');
script.src = "https://link_to_load";
document.getElementsByTagName('head')[0].appendChild(script);
},
4000);
</script>