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>.
Related
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.
So I have a static HTML page that I cannot edit and I need to add jQuery to it and then do some div manipulation (height) on document ready. I found this post which describes how to insert it into a page, which works great. I added that to my javascript file and it inserts it into the page. The problem is that I need to perform some actions on $(document).ready() on that same page, but it says that $ is undefined.
What I would like to do is something like this:
var script = document.createElement('script');
script.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
$(document).ready(function() {
// Resize my div's to the browser window
});
But I can't seem to get it to work. Is this possible? How?
var script = document.createElement('script');
script.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js';
script.type = 'text/javascript';
script.onload = resize; //most browsers
script.onreadystatechange = function() { //ie
if (this.readyState == 'complete') {
resize();
}
}
document.getElementsByTagName('head')[0].appendChild(script);
function resize() {
//code goes here
}
This is due to the ready event firing before the JS jQuery file has loaded. Here is a good tutorial on how to do it.
http://www.ejeliot.com/blog/109
This isn't going to help your page performance though to load your jQuery like this. You should really try to minimize your JS and use as few requests as possible for the best user experience.
Also, you don't need to write
$(document).ready(function() { });
You can just write
$(function() { });
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.
I am including jQuery in background_page like this,
<script type="text/javascript" src="libs/jquery.js"></script>
Here's the problem:
In websites, where jQuery plugins are used (with jQuery.extend method), they do not work when my extension is installed.
I guess this is because I had my jQuery.js over 'their' jQuery.js' file and all .extend do not work.
So, I thought of adding jQuery.js only when its not avaialable. So, I tried adding jQuery like this,
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "libs/jquery.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
But no luck.
Can someone suggest me a good way to add jQuery.js file in background page.
I really like your approach here, but I would recommend enwrapping your declaration inside of a load event listener:
if (window.addEventListener) {
window.addEventListener('load', init, false);
} else if (window.attachEvent) { // for IE8 and below
window.attachEvent('onload', init);
}
function init() {
if (typeof jQuery === 'undefined') {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "libs/jquery.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
I think the issue may be that at the time you're asking if jQuery is an object, that the DOM hasn't loaded yet.
Alternatively, you can load jQuery via your Manifest File under content_scripts: http://code.google.com/chrome/extensions/dev/content_scripts.html
Found an answer later,
Doing
jQuery.nocConflict
jQ = jQuery.noConflict
and replacing $ with jQ everywhere, solved the problem.
Conclusion: content_scripts can also interfere with webpage javascripts.
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>