How to delay a javascript from loading - javascript

I have this Javascript that takes AGES to load and slows the website down on load so bad, like 5 seconds to load! I was wondering if I could make the JavaScript load after the website has loaded, so the Javascript doesnt slow the site down on load?

Try including your file after the page loads,
window.addEventListener("load",function() {
var elem = document.createElement('script');
elem.type = 'text/javascript';
elem.src = 'yourfile.js';
document.body.appendChild(elem);
},false);

The latest method that is widely used is jQuery.
Inserting this tag in your head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
And in the bottom of the body (right before the body end)
<script type="text/javascript">
$(document).ready(function () {
//// INSERT YOUR JAVASCRIPT CODE HERE /////
}); //end of document ready
</script>
</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.

How to include jQuery library in Javascript without <script src="">

I need to include jQuery library in javascript file (john.js) remotely. I have tried this without any luck;
(function(d, t) {
var g = d.createElement(t), // create a script tag
s = d.getElementsByTagName(t)[0]; // find the first script tag in the document
g.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
s.parentNode.insertBefore(g, s); // append the script to the DOM
}(document, 'script'));
$( document ).ready(function() {
// My jquery works here
});
I want to fetch a script in javascript way. What is the correct way to do that ?
The error here is that JQuery is not loaded yet when this code is executed:
$(document).ready(function() { .. }
As is, you get an error like this: $ is undefined (or similar)
You should use the onload event of created script element to be sure it is loaded Jquery.
This sample shown how you can achieve your goal. Good Luck.
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
newScript.onload = function() {
alert("Script is ready!");
$(document).ready(function() {
alert("JQuery is ready!");
});
};
var head = document.getElementsByTagName("head")[0];
head.appendChild(newScript);
Here is the answer on how to fetch, coming from an other post :
Adding <script> element to the DOM and have the javascript run?
That beeing said another issue you may have is that when you call your
$( document ).ready(function() {
// My jquery works here
});
Jquery may not be loaded yet
so you can try a recursive function to check if jquery has been loaded with something like that (not teste)...
function launch(callBack){
if (window.jQuery) {
callBack();
} else {
setTimeout(function(){launch(callBack);},100);
}
}
launch(function(){
$( document ).ready(function() {
// My jquery works here
});
});
You can use a combination of an XMLHttpRequest and eval to fetch the javascript file dynamically like getScript does for jQuery.
See my fiddle.
Typically the jquery is called in the html file before custom javascript files are called:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="app.js"></script>

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>

loading a backup copy of jQuery when CDN is down

I have this code in a script we use for initializing all of our applications, it loads the jQuery from the google CDN amongst several other things that all of our applications require. Then when we load the specific program functionality we check to make sure that jquery has loaded, in case the CDN is down. The problem I am running into is it is still loading the second one. If I add a simple alert("Test"); after the line headTag.appendChild(jqTag); it works perfectly, but if I remove the alert it uses the second one. What gives?
They are loaded like so:
<script type="text/javascript" src="i-initializer.js"></script>
<script type="text/javascript" src="i-program.js"></script>
initializer script:
if(typeof jQuery=='undefined'){
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
headTag.appendChild(jqTag);
}
Then in another script we have the following:
if(typeof jQuery=='undefined'){
var header = document.getElementsByTagName("head")[0];
var qtag = document.createElement('script');
qtag.type = 'text/javascript';
qtag.src = 'http://feedback.oursite.com/scripts/jquery-1.8.3.min.js';
qtag.onload = checkjQueryUI;
header.appendChild(qtag);
}
else
{
jQCode();
}
jQCode() {
...
}
This is the technique used by HTML5 Boilerplate. First it loads the Google CDN script, then immediately checks if the global jQuery object exists -- if it doesn't, the CDN failed and a local copy is loaded instead.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.3.min.js"><\/script>')</script>
Your fallback code loads jQuery asynchronously.
That means that the rest of your scripts run before jQuery loads.
Adding an alert() call forces the rest of your code to wait (until you click OK); by the time that happens, jQuery will have loaded.
Instead, you can emit a new <script> tag using document.write() to load it synchronously.
Alternatively, you could wrap the rest of your code in a callback and call the callback(s) after jQuery loads.
If you do it this way, you should use a script loader library, which will handle all of that for you.

Load scripts after page has loaded?

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>

Categories

Resources