Load scripts after page has loaded? - javascript

Is it possible to load certain scripts like
<script type="text/javascript" src="somescript.js"></script>
when the rest of the page has loaded?
Imagine I have a few larger script files like this that are not needed when the page is loaded. E.g. I'm using the Google Maps API that is only used when a button is clicked (so not on page load).
Is it possible to load the rest of the page first, before processing all those script tags in my head?

In JQuery you could do this on document ready
$.getScript("somescript.js", function(){
alert("Script loaded and executed.");
});

simply you can add into that script file defer parameter
<script src="pathToJs" defer></script>
you can check this question as well

It is possible. I was doing a similar thing in an AJAX intensive site, but I was loading the Google Charts API. Here is the code I used to load the Google Charts API when a button was clicked on the page.
function loadGoogleChartsAPI() {
var script = document.createElement("script");
// This script has a callback function that will run when the script has
// finished loading.
script.src = "http://www.google.com/jsapi?callback=loadGraphs";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
function loadGraphs() {
// Add callback function here.
}
This uses a callback function that will run when the script has loaded.

No one mentioned these?
$(window).load(function(){
// do something
});
or
$(window).bind("load", function() {
// do something
});

$(document).ready(function() {
var ss = document.createElement("script");
ss.src = "somescript.js";
ss.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(ss);
});

Please see my code. The onload event will occur when the script has finished loading. Or the onerror event will occur.
function loadJavaScript() {
var script = document.createElement("script");
script.src = "javaScript.js";
script.type = "text/javascript";
script.onload = function () {
console.log('script was loaded successfully');
}
script.onerror = function (e) {
console.error('script.onerror');
}
document.getElementsByTagName("head")[0].appendChild(script);
}
Thanks to answer.
Also see my code of the load of the script.

use the getScript method of jquery! or try simply to put this script on the end of the page?

Yes, this is possible by dynamically injecting the JavaScript files from code. There are lots of libraries which you can use:RequireJS, HeadJS etc. Recently I found this document which compares lots of JavaScript loader libraries.

To just allow the page to show before your script is loaded, use the async attribute:
<script src="//url/to/script.js" async></script>
To hide the loading spinner in the browser, append the script tag after the page finished loading:
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = '//url/to/script.js';
document.getElementsByTagName('body')[0].appendChild(script);
});
</script>

Yep, that's completely possible. Add an onLoad="foo();" event to your <body> tag and have it invoke your scripts. You'll need to wrap your external JS in a function and do something like:
//EXTERNAL JS (jsstuff.js)
function Mojo() {
document.getElementById('snacks').style.visibility = "visible";
alert("we are victorious!");
}
//YOUR HTML
<html>
<head>
<script type='text/javascript'></script>
</head>
<body onLoad='Mojo();'>
<div id='snacks'>
<img src='bigdarnimage.png'>
</div>
</body>
</html>

Related

Loading inline jQuery scripts along with deferred and async scripts

I am working on a website and working on its Page Speed Insights and have a
Eliminate render-blocking JavaScript and CSS in above-the-fold content
So basically what happen is I have two external javascript import on top of the page which is:
<script src="/remotestaff_2015/js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="/remotestaff_2015/js/bootstrap.min.js" type="text/javascript"></script>
This website has lot of javascripts but some are at the bottom of the page after the <body> tag. So my problem is those two on the top. To fix the render block I already searched on google and found out that I can use the defer or async attribute. My problem is that there are some modules on the website that has inline javascripts like:
<script type="text/javascript">
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
if ($("#wrapper").hasClass("toggled")) {
$(".color-fade").css("opacity", ".5");
} else {
$(".color-fade").css("opacity", "1");
}
});
So if I put defer on my jquery file I'll have an error on my inline javascripts because it will load without the jquery loaded yet. Is there a way to fix this inline scripts or somehow make them run after the deferred jquery or other js files has been loaded? I don't want to put those inline scripts in other file.
According to MDN:
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Therefore let your inline script wait for the document and the deferred scripts to be loaded. The DOMContentLoaded event will fire when that has happened:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Inline scripts go here
});
</script>
Notice that the $(document).ready(function() is not required any more, because that would wait for the same event (DOMContentLoaded).
you can load your js dynamically in
$(window).bind("load", function() {
// code here
});
for dynamically loading scripts you ca use code
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);
Please let me know if it helped you.
I would do this to make everything clean. Load jQuery file without defer and define menu toggling event in HTML head.
<script src="/remotestaff_2015/js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
// option 1
/* $('#menu-toggle').click(function() {
// your code
}); */
});
// option 2
$(document).on('click', '#menu-toggle', function() {
// your code
});
</script>
Now you can render the element anywhere in HTML body or even from AJAX callback.

Inserting a <script> tag dynamically via jQuery

I'm trying to add a widget to the page in run-time. Based on this post, I wrote the code below. Unfortunately, it doesn't show anything. Can anybody tell me why?
<script type="text/javascript">
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// Use any selector
$(".testWidget").append(s);
});
</script>
<div class="testWidget">
</div>
If I put the same script as below, it works and shows some information on the page. However, I should insert the script dynamically, not as static.
<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>
You should be getting this warning in the console, Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Here's a way around that:
<script type="text/javascript">
$(document).ready(function () {
// Save a copy of the document.write method
var oldWrite = document.write;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// After script is loaded, revert document.write to the original
s.onload = function () {
document.write = oldWrite;
};
var $testWidget = $('.testWidget');
// Redefine document.write to make the script's call work
document.write = function (html) {
$testWidget.html(html);
};
$testWidget.append(s);
});
</script>
The script tag you include programatically has to be parsed by the browser. Just by inserting the script tag the included code is not parsed by the JavaScript interpreter.
If you explain what you want to finally achieve I am pretty sure that must be a simpler way to do it.

Defering java script

I want to defer the following script. I need it to launch only after Keyup (aftet the mouse was clicked then I start typing). this is delaying page load I specially want to delay jquery.js.. see script below..
<script type="text/javascript" src="scripts/jQuery.js"></script>
<script defer type="text/javascript">
$(document).ready(function(){
$("#searchquery").keyup(function(){
$.get("suggest.php", {searchquery: $(this).val()}, function(data){
$("datalist").empty();
$("datalist").html(data);
});
});
});
$(document).ready(function(){
$("#searchquery2").keyup(function(){
$.get("suggest1.php", {searchquery2: $(this).val()}, function(data){
$("datalist").empty();
$("datalist").html(data);
});
});
});
</script>
The most reliable method for deferring scripts seems to be to insert a <script> element into the page at runtime. If you're deferring things like jQuery, then you'll probably want to load them once the DOM is loaded rather than when the user performs an action, which will typically get your script loaded sooner and probably give better performance to the user (e.g. when they first click something, they won't have to wait for jQuery to load before something awesome happens).
Below is an example of loading a script in about the same way as Google Analytics. If your browser supports the JS API I'm using, and the events I'm listening to, and console.log(), then you should see that window.jQuery is logged as undefined when the page loads, and then a function five seconds later (as long as jQuery loads by then!).
Disclaimer: Absolutely nothing has been done here to ensure cross-browser compatibility. This is just a simple demonstration of deferring a script.
<!doctype html>
<html>
<head></head>
<body>
<script>
(function() {
function init() {
loadDeferredScript('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js');
console.log(window.jQuery);
setTimeout(function() { console.log(window.jQuery); }, 5000);
}
function loadDeferredScript(src) {
var script = document.createElement('script');
script.src = src;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
}
document.addEventListener('DOMContentLoaded', init);
})();
</script>
</body>
</html>

Add jquery script via script file

I have script (myscript.js) which create div and animate div in any HTML page. my script is using Jquery animation function
I am currently using following code (it's sample snippet)
<script src="jquery.js"><script>
<script src="myscript.js"><script>
But is this possible to use only following code which can automatically add JQuery library also?
<script src="myscript.js"><script>
Insert this on top of your myscript.js
var h=document.getElementsByTagName('head')[0];
var s=document.createElement('script');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
h.appendChild(s);
but you will have to wait until script loaded using waitforload function
function w4l(){
if (typeof jQuery != "function"){
setTimeout("w4l()", 1000);
return;
}else{
//Do Jquery thing
}
}
w4l();
or just simply copy all jquery.js code file into your myscript.js, AKA merge 2 file into one
To make sure that the rest of myscript.js doesn't get executed before jQuery is loaded, use something like this:
function dostuff() {
//animate elements, etc.
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'jquery.js';
script.onreadystatechange = dostuff;
script.onload = dostuff;
head.appendChild(script);
Note: it's a bit unclear why you wouldn't want to explicitly add the jQuery part in your head.

Delay Loading Javascript to speed my Joomla

I'm using joomla site, and Forced to use extra java script.
My Question is:
How to force loading the javascript ONLY after page complete
I dont mean DELAY them, But make them in Queue till the page complete loading.
I tried many of links tutorial but nothing helps me.
Please,
Would you provide correct example in order to make me understand.
Example to JS file I inserted to buttom of my page:
<script src="/js/easing.js" type="text/javascript"></script>
Can you provide Jquery code to force all those script to wait till the page load complete?
Thank you
Tariq
Ales Kotnik answer's in great, and also if you want to do it in your own specifiec time, you can do something like that:
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);
}
this will load a script only when you call it, and then you activate it like this:
<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>
Use <script src="..." async="async"/>. In modern browsers (HTML5)it will spawn fetching javascript files separately and won't delay loading of your HTML. You can just put script tags at the end of your <body>.

Categories

Resources