What is the distinction between head.ready() and head.load()? - javascript

Using the JS loader head.js I'm having a bit of a hard time distinguishing the subtle differences between head.ready() and head.load().
head.ready('jquery.js', function(){//Do something});
VS
head.load('jquery.js', function(){//Do something});
As far as I understand both seem to load 'jquery.js' and then perform a callback when it is loaded. However, in practice I get some edge cases where head.load doesn't work as expected in Firefox making me think I am not understanding where to use head.load and where to use head.ready.

Reading the API it seems like head.load loads the content, but head.ready is an Event Listener, you can also add a callback to head.load and would work too, but head.load is the only one who can actually load the resources, head.ready not.
EDIT: An example
<html>
<head>
<script src="head.min.js"></script>
<script>
// this loads jquery asyncrounously & in parallel
head.load("jquery.min.js");
</script>
</head>
<body>
<!-- some content-->
<!-- injected via a module or an include -->
<script>
// some function that depends on jquery
head.ready("jquery.min.js", function () {
// this will only be executed once jquery has finished loading
$(".main").hide();
});
</script>
<!-- some content-->
</body>
</html>

Related

Loading Section not disappearing on first load

I made a loader that uses css and javascript to play an animation. On loading the site for the first time the animation sometimes doesn't play leaving a blank white screen. I believe it has something to do with caching on the second load that makes it work. Thanks in advance.
HTML:
<section id="loading">
<div class="circle spin"></div>
<img src="src/j2.svg" alt="J2 Logo">
</section>
<link rel="stylesheet" href="css/loading.css">
<script type="text/javascript" src="scripts/loading.js"></script>
loading.css:
https://pastebin.com/E16PMTtQ
loading.js:
https://pastebin.com/1X09KatC
The websites link is https://j2.business
With a quick look at your code it looks like all code is executed when the javascript-file gets loaded. This could be a timing-issue (your javascript-file is retrieved faster than your HTML-page: the elements it wants to act on are not available yet).
With jQuery you can quickly solve that by embedding your variables and functions in this holder:
$( document ).ready(function() {
// place code here, the document is waiting
});
Because you are not using jQuery you could use this:
add the "defer" attribute.
<script type="text/javascript" src="scripts/loading.js" defer></script>
This should be enough, specs found here:
https://www.w3schools.com/tags/att_script_defer.asp
Or if you want only some functions executed when the document is loaded you could use the function which all browsers support:
(function() {
// place code here, the document is waiting
})();

Includes taking a long time to load and you can see them loading

I’m including one HTML file in another, as a way to reuse my header and navigation generation logic.
The trouble is that when I browse to pages on my site, I can see the HTML that isn’t included in the include files load first. Only then you can see the menus and banners load afterwards. I’d like everything to appear to load at the same time.
Here's the rendered HTML.
And here’s a code snippet showing you how I generate these pages:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
<script>
$(function(){
$("#includeHeader").load("includes/templates/header.html");
$("#includeNavigation").load("includes/templates/navigation.html");
});
</script>
<div id="includeHeader"></div>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<div id="includeNavigation"></div>
I’m currently working with the code to try to move any external libraries / CSS to the bottom of the page vs. in the header. But so far, that hasn’t really changed or improved anything.
You should use one of the templating languages.
If your includes are simple HTML files then you could use Handlebars or Dust - you could just copy your code and that's it, then in Javascript you would need just render these templates - see the documentation.
You could use Jade/Pug instead, but its syntax is different from the HTML, so that's not just question of copy-paste.
You are using $(handler) to load them, which is a form for $.ready(). So it waits for the document to load everything before loading your header.html and navigation.html.
Try
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
</head>
<body>
<div id="includeHeader"></div>
<script>
$("#includeHeader").load("includes/templates/header.html");
$("#includeNavigation").load("includes/templates/navigation.html");
</script>
</body>
Your problem is that the load function does not run until the document.ready event has fired. Which is probably after your page has started rendering. To get everything to appear at the same time you could use the callback from .load to show everything. So everything is hidden,
$( "#result" ).load( "ajax/test.html", function() {
/// show your stuff
});
You will of course need to know both has loaded.
I would recommend not using javascript to render HTML from a static path and would use a server side lang instead for speed.
I think it make some level fast its not waiting for load all dom element, I am considering #includeNavigation element is under #includeHeader element
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
</head>
<body>
<div id="includeHeader"></div>
<script>
$("#includeHeader").load("includes/templates/header.html", function(data){
console.log("header loaded");
$("#includeNavigation").load("includes/templates/navigation.html", function(data){
console.log("navigation loaded");
});
});
</script>
</body>

Best way to fire events when single elements in the document becomes ready

I'm developing a web application that because of performance concerns is heavily reliant on Ajax functionality. I'm attempting to make parts of each page available while longer running modules load.
The issue is that I want to kick off the Ajax requests as soon as possible (in the head of the document). This part works fine; the issue is on rare occasion, the Ajax call will come back before the area that I want to load the Ajax data into is present on the page. This causes the data to not be loaded.
To get around the issue I started using script tags below each of my containers that resolve a JQuery promise to let the code know that the area is available.
EDIT: I want to load the data into the area as soon as it becomes available (before full document load).
The current pseudo code looks like this:
<head>
<script>
var areaAvailablePromise = new $.Deferred();
$.when(areaAvailablePromise, myAjaxFunction()).then(function(){
// load data into the element.
});
</script>
</head>
<!-- much later in the document -->
<div class="divIWantToLoadAjaxContentInto"></div>
<script>
areaAvailablePromise.resolve();
</script>
My question is: is there ANY better way to handle this situation? Every one knows that inline scripts are blocking and are bad for performance. Also, I feel that this is going to lead to cluttered code with micro-script tags all over the place.
Put your (whole) <script> tag just after the element.
HTML is parsed from top to bottom, so the element will be loaded already.
No. There really is no better way to my knowledge.
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="q.min.js"></script>
<script>
var elD = Q.defer();
var dataP = Q($.ajax(…));
Q.spread([elD.promise, dataP], function (el, data) {
…
}).done();
</script>
</head>
<body>
…
<div id="foo"></div>
<script>elD.resolve($("#foo"));</script>
…
</body>
</html>
you can use:
$(document).ready( handler )
(recommended)and also has contracted form:
$(handler)
exemple:
$(function(){
alert("OK");
})
read more: http://api.jquery.com/ready/

window.onload equivalent after modifying the DOM?

When a page first loads we can use window.onload to make sure that all resources have loaded before we do something.
My question is, if we modify the DOM (e.g. inserting some html based on an ajax request), is there any event that will fire when the document is in the 'loaded' state again? (e.g. when the html inserted contains multiple images).
(Solution with jQuery would be fine).
The short answer:
NO.
The long answer:
if you know what you are looking for you can use mutation observers (https://developer.mozilla.org/en-US/docs/DOM/MutationObserver). it is only support in new browser, and in some version of chrome it has memory leaks when used with closures.
BTW,
document.ready doesn't tell you if all (or any..) of the resources were loaded. it only tell you well, that the dom is ready (that is the load function, which will only fire after all resources (well, any resources that isn't requested using a javascript) were downloaded).
You can use .done().
Description: Add handlers to be called when the Deferred object is resolved.
Also there is jQuery plugin See Here
I would say YES (I do not know if this is supported by all browsers. I use it in safari and chrome)
Testcase you can find here : http://maakmenietgek.nl/testcases/domready/ Please note that I cannot get it work in a fiddle, that's why a standalone testcase
The index.html looks like this
<!DOCTYPE html>
<head>
<title>Testcase</title>
<script src="jquery-1.8.2.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#clickme').click(function() {
$.get('ajaxdata.html', function(data) {
$('#addhere').html(data);
});
});
})
</script>
</head>
<body>
<p id="clickme">clickme</p>
<div id="addhere">
</div>
</body>
</html>
The data loaded with the $.get call looks like this
<p>added data</p>
<script type="text/javascript">
$(document).ready(function() {
alert('added data');
});
</script>
The alert shows after the html has been added to the DOM

jQuery $(document).ready () fires twice

I've been sifting around the web trying to find out whats going on here and I have not been able to get a concrete answer.
I have one $(document).ready on my site that seams to run multiple times regardless of the code that is inside it.
I've read up on the bug reports for jQuery about how the .ready event will fire twice if you have an exception that occurs within your statement. However even when I have the following code it still runs twice:
$(document).ready(function() {
try{
console.log('ready');
}
catch(e){
console.log(e);
}
});
In the console all I see is "ready" logged twice. Is it possible that another .ready with an exception in it would cause an issue? My understanding was that all .ready tags were independent of each other, but I cannot seem to find where this is coming into play?
Here is the head block for the site:
<head>
<title>${path.title}</title>
<meta name="Description" content="${path.description}" />
<link href="${cssHost}${path.pathCss}" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="media/js/fancybox/jquery.fancybox.pack.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/landing.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/functions.js" type="text/javascript"><!-- --> </script>
<script src="/media/es/jobsite/js/jobParsing.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="/media/es/jobsite/js/queryNormilization.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.metadata.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.form.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery.i18n.properties-min.js" type="text/javascript" charset="utf-8"><!----></script>
<script type="text/javascript" charset="utf-8">
function updateBannerLink() {
var s4 = location.hash.substring(1);
$("#banner").attr('href','http://INTELATRACKING.ORG/?a=12240&c=29258&s4='+s4+'&s5=^');
}
</script>
</head>
Pay no attention to the JSP variables, but as you can see i'm only calling the functions.js file once (which is where the .ready function exists)
The ready event cannot fire twice. What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within which causes the browser to re-execute the script block.
This can be avoided by including script tags in the <head> or before the closing </body> tag and not using $('body').wrapInner();. using $('body').html($('body').html().replace(...)); has the same effect.
It happened to me also, but I realized that the script had been included twice because of a bad merge.
This happened to me when using KendoUI... invoking a popup window would cause the document.ready event to fire multiple times. The easy solution is to set a global flag so that it only runs once:
var pageInitialized = false;
$(function()
{
if(pageInitialized) return;
pageInitialized = true;
// Put your init logic here.
});
It's sort of hack-ish, but it works.
Make sure you don't include JS file twice. That was my case
You might consider to use
window.onload
instead of
$(document).ready
try putting this in your functions.js to prevent it from being executed twice :
var checkit = window.check_var;
if(checkit === undefined){ //file never entered. the global var was not set.
window.check_var = 1;
}
else {
//your functions.js content
}
however i suggest that you look more into it to see where are you calling the second time.
I had a similar problem when I was trying to refresh a partial. I called a return ActionResult instead of a return PartialViewResult. The ActionResult caused my ready() to run twice.
There is a possibility to encounter this problem when you add same controller twice in the html.
For an instance:
[js]
app.controller('AppCtrl', function ($scope) {
$(document).ready(function () {
alert("Hello");
//this will call twice
});
});
[html]
//controller mentioned for the first time
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
//same controller mentioned again
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
I had a similar issue today. A <button type="submit"> caused the $(document).ready(...) event to fire again in my case. Changing the code to <button type="button"> solved the issue for me.
See document.ready function called again after submit button? here on stackoverflow for more details.
In my case $(document).ready was firing twice because of bad CSS, check if any part of your CSS has background-image: url('');
If the iframe doesnt show anything and is used for other reasons (like uploading a file without reload) you can do something like this :
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
Notice that src is not included that prevents the second on ready trigger on the document.
I had this problem with window.load function was executed twice:
The reason was because I had reference to the same javascript-file in the main page as well as a .net usercontrol. When I removed the reference in the main page, the load-function was only executed once.
I had this happen to me this morning... and what I discovered after closely examining some html code in a jquery modal form that I had recently manipulated, that I'd accidentally removed a closing table tag. I haven't taken the time yet to fully understand why that caused the document.ready function to be called twice, but it did. Adding the closing table tag fixed this issue.
jQuery JavaScript Library v1.8.3 (yes, it is a legacy app)
My problem was that I had tags referencing my JS file in both my index.cshtml file AND my _Layout.cshtml. This was causing the document.ready function to fire twice, which was causing DataTables to bomb.

Categories