In order to optimize the load of my document, I use to load jQuery async like that
<script async type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
Then I call a script using jQuery :
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
It returns me that jquery is not defined.
I don't know what should I use, I though that .readyfunction would wait until all document is loaded before calling it.
The same for Bootstrap library, It tells me that jQuery is not defined.
I've tried to ask the script to be loaded at the end, but it still does not work properly.
Since jquery script is loaded asynchronously, jquery is not loaded on the moment your script is executing. So you need to wait for it to load by subscribing on load event like this:
<script async id="jquery" type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
Then listen for a load event on this element
<script type="text/javascript">
document.getElementById('jquery').addEventListener('load', function () {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
But I don't know why someone wants to do things like this.
To optimize page loading speed it is better to put all you javascript at the end of the body, so content will be loaded first, and scripts won't delay page rendering event if it's synchronously loaded.
Edit: I agree with comment and consider previous paragraph not the best way of loading jQuery to the page
Question Script Tag - async & defer has good answer to your problem.
In a nutshell you cannot load jQuery, or other library, asyncronously when some other script depends on it without some additional asyncronous handling for executing the scripts depending on the library.
That is my solution:
<script async type="text/javascript" src="path_to_jquery" id="jquery_script_tag">
</script>
<script>
if ( !('jQuery' in window) )
{
window.jQueryQueue = [];
//define temporary jQuery function
window.jQuery = function(){
//just save function parameters to queue
jQueryQueue.push( arguments );
}
document.getElementById('jquery_script_tag').addEventListener('load', function(){
//call jQuery with parameters saved in queue, after it loaded
for ( var i in jQueryQueue )
jQuery.apply( document, jQueryQueue[i] );
});
}
</script>
This code defines a temporary jQuery function if it is yet not defined. The function saves all jQuery function calls to queue while the real jQuery has not yet loaded (instead of calling undefined jQuery function). And when jQuery has loaded, it calls the jQuery functions in the queue with the same parameters as called before.
jQuery, and all components that depend on jQuery (including Bootstrap), depend on hooking the DOMContentLoaded event to set up events.
This means jQuery (and anything that uses $(function() {...})) must be downloaded before DOMContentLoaded fires, or it never hooks up its events.
In turn, that means <script async ... will be unreliable, breaking whenever jQuery takes longer to download than the page content does.
Unfortunately <script defer ... doesn't work either thanks to jQuery trying to fire as soon as the document.readyState === "interactive".
You can load content and then load jQuery by putting the <script> at the end of the <body> but this will result in a noticeable pause between the page appearing and any of the jQuery firing - users won't be able to click on anything, visual components won't appear, and so on.
This way works just fine:
<script charset="utf-8" type="text/javascript">
var intervalID = window.setInterval(function(){
if(window.jQuery){
clearInterval(intervalID);
console.log('Loaded');
/* Your code here */
}
},1000);
</script>
You Used Async Loading When You Try Access Jquery It Not Loaded By Browser You Can Access Jquery After Page Loading Is Complete .
Load Jquery Normally To Fix Your Problem .
Related
My index.html include two javascript codes which are plugin.js and main.js(main include after plugin),
I want to make plugin.js as a reusable plugin, like checking if the index.html file has any elements which have click-me class attribute, if index.html has this kind of elements, then set every this kind of elements an eventListener.
I want my window.onload function ALWAYS in main.js rather than plugin.js, but in this case I cant' get DOM object by className in plugin.js, I also don't want to call any function of plugin.js in main.js.
Does anyone ahs any idea?
You can just include the scripts after the body.
<body>
</body>
<!-- add your scripts here -->
Then you don't need to check if the document is ready anymore, this has the drawback of only starting the download after the page is fully rendered.
Another possibility is using defer
<script type="text/javascript" src="plugin.js" defer></script>
<script type="text/javascript" src="main.js" defer></script>
This way scripts are downloaded as soon as possible but are executed only after the page is ready, and in order.
A more detailed answer here
Well, you should properly use onload as an event listener:
window.addEventListener("load", function() {
});
This can be added as many times as you wish, both in main.js and plugin.js.
Additionally, it's better to use DOMContentLoaded event, because it doesn't wait on loading images. That's really important, if you rely on window.onload, just one pending image can make your page useless for first 10 seconds of the visit. It's used like this:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
It has compatibility issues however, so I recommend using some library.
Oh and last thing - don't link your scripts before body unless needed. They block parsing of the page.
Why don't you just check if the clicked element have the click-me class from the root? It makes you declare only one listener on the body.
function listener(event) {
if(event.target.classList.contains("click-me")) {
// Do something
}
}
document.body.addEventListener("click", listener, true);
I'm attempting to get some jquery code to run after a sharepoint page loads, the code being:
$(".ms-commentcollapse-icon").click();
I've been using the following to load the code after the page loads, but it does not seem to be very reliable (it will work sometimes and other times it wont):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".ms-commentcollapse-icon").click();
});
</script>
are there any other good methods for achieving this? I'm not sure what's going on, sharepoint could be at fault, but I figured I would try fiddling around with the script a bit more first.
You could use an auto-executing function:
<script type="text/javascript">
(function () {
$(".ms-commentcollapse-icon").click();
} ());
</script>
If this is SharePoint 2010 or above, you can use ExecuteOrDelayUntilScriptLoaded(yourfunction,"SP.JS") to keep your code from firing until after the SP.JS library has loaded (or you can put any other library in the second parameter for a similar effect).
If this is in a web part and you don't want it to execute until other web parts on the page are fully loaded, make sure the web part containing the script is below the other web parts.
As a last resort, you could execute it on a delay using setTimeout or setInterval, but that's ugly.
You can prevent the default behaviour by using e.preventDefault(); within the function.
<script type="text/javascript">
$(".ms-commentcollapse-icon").click(function(e) {
// We're going to stop the default behavior
e.preventDefault();
//some code here
});
</script>
Is there anyway to check if page is fully loaded.Something like this http://msdn.microsoft.com/en-us/library/system.web.ui.page.loadcomplete.aspx but for JAVA.
If you intend to execute logic on the client side when the page is loaded, you might be interested in the Javascript onload event.
Or, even better, consider using jQuery and use the ready() function to execute your logic.
Just a short example using jQuery:
$(document).ready(function() {
alert("The document, including all assets such as images, has been completely received");
});
Not directly in java, since it is probably not running in the browser, but you can do it with javascript
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">var myFunc = function() {
alert("The page is fully loaded!");
};
window.onload = myFunc;
</script>
</head>
you can use the normal onload()
<body onload="yourFunctionHere()">
or the JQuery version
$(document).ready(function() {
yourFunctionHere();
});
1. JQuery will help you:
there is $(document).ready() which tell you that the browser is loaded.
Example:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images).
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
2.Window onload is another JavaScript approach:
window.onload=function(){SomeJavaScriptCode};
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Note: The main difference is that document.ready() event gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully, while window.onload will wait until all your contents are loaded fully.
We can have more than one document.ready() function in a page where we can have only one onload function.
Not in Java, no.
You'll need Javascript:
<script>
window.onload = function() {
alert('Loading Complete!');
}
</script>
I need to optimize the load time of a web application which contains lots of javascript files included in each of it's HTML pages. I want to try head.js in one such page to see if it improves load time. There are lots of $(document).ready(callback) callbacks in those JS files which are invoked when DOM is loaded while head.js is still downloading remaining JS files.
Is there a way I could tell jQuery not to trigger ready event on its own, rather let me trigger it from inside the ready callback of head.js?
I am unsure as to why you'd want to trigger the document ready event manually.
Instead, subscribe and publish your own events using jQuery's built-in trigger & bind functionality. This is best practice and the optimal solution.
Working JSFiddle Demo
I have made a small experiment. Something like:
<html>
<head>
<script src="head.js"></script>
<script src="jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
jQuery("document").ready(function() {
console.log("ready.document");
});
</script>
...
<script type="text/javascript">
head.js("a.js", "b.js", "c.js", "test.js", function() {
console.log("init.scripts");
var millis = 2000;
var date = new Date();
var curDate = null;
do {curDate = new Date(); }
while(curDate-date < millis);
jQuery("#ddd").text(testTT);
console.log("init.end");
});
</script>
... a lot of html content ...
<div id="ddd"></div>
...
<script type="text/javascript" >
console.log("last line");
</script>
</body>
The test.js writes to console and defines testTT. The result is following
last line
init.testTT
init.scripts
init.end
ready.document
Thus, in this simple case (using jQuery 1.8), first the code in loaded *.js is executed then head.js on init event is generated, finally jQuery ready event is generated. So it should be fine to wait until JQuery generates ready event.
However if this is still an issue you could do the following.
head.js("a.js", "b.js", "c.js", function() {
jQuery("document").ready(function() {
jQuery("body").trigger("your_event");
});
});
and instead of listening to jQuery("document").ready... in your *.js start listen to the custom event you are triggering jQuery("body").on("your_event", handler).
create a function register it in document ready
$(document).ready(readyFunc);
readyFunction(){
/// something to do;
}
if you like to use them manually, just need call the readyFunction();
Disclaimer: I am new to jQuery.
I am trying to implement a fadeOut effect in jQuery for a div block, and then fadeIn effect on two other div blocks.
However, these effects are only working in the Chrome browser (i.e. they won't work in Safari, FireFox, Opera) which is rather perplexing to me. I have tried clearing my cache in case it was storing an old file, but none of that seemed to do anything.
Basic idea (stored in mainsite.js file):
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
So when a div tag with the id of videoThumbnail_XYZ is clicked, it starts the fadeOut and fadeIn calls on the other div tags.
I am loading my javascript files into the page in this order (so jQuery is loaded first):
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script async="" type="text/javascript" src="javascripts/mainsite.js"></script>
Any guidance you could give is greatly appreciated!
Make sure the DOM is fully loaded before your code runs.
A common way of doing this when using jQuery is to wrap your code like this.
$(function() {
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
});
This is a shortcut for wrapping your code in a .ready() handler, which ensure that the DOM is loaded before your code runs.
If you don't use some means of ensuring that the DOM is loaded, then the #videoThumbnail_XYZ element may not exist when you try to select it.
Another approach would be to place your javascript code after your content, but inside the closing </body> tag.
<!DOCTYPE html>
<html>
<head><title>your title</title></head>
<body>
<!-- your other content -->
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script async="" type="text/javascript" src="javascripts/mainsite.js"></script>
</body>
</html>
If mainsite.js is being included before your div is rendered, that might be throwing the browsers for a loop. Try wrapping this around your click handler setup:
$(document).ready(function(){
// your function here
});
That'll make sure that isn't run before the DOM is ready.
Also, you might consider putting the fadeIn calls in the callback function of your fadeOut, so if you decide to change the duration later on, you only have to change it in one place.
The way that'd look is like this:
$("#thumbnailDescription_XYZ").fadeOut(300,function(){
$("#videoPlayer_XYZ").fadeIn(100);
$("#videoHiddenOptions_XYZ").fadeIn(100);
});
I see you have a delay set to the same duration your fadeOut is, I would recommend instead of delaying which in essence your waiting for the animation to complete that instead you use the callback function.
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300, function() {
$("#videoPlayer_XYZ").fadeIn(100);
$("#videoHiddenOptions_XYZ").fadeIn(100);
});
});
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
$(document).ready(function(){
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
});
All three of the following syntaxes are equivalent:
* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)