Javascript - DOM ready after loading external javascript? - javascript

Is the DOM always ready when my external scripts have finished loading?
<head>
<script type="text/javascript" src="base.js"></script>
</head>
Inside base.js, I have an object that loads external scripts. It uses the following method to do so:
var head = document.getElementsByTagName("head")[0],
scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.onreadystatechange = function () {
if (this.readyState === "complete") onModuleLoaded();
};
scriptElement.onload = onModuleLoaded;
scriptElement.src = "externalScript.js";
head.appendChild(scriptElement);
Now, when all external scripts have been loaded, a callback function is called. My question is: Is this callback function suitable to place the
rest of my javascript code in? This code needs the DOM to be ready.
My scripts also use jQuery. But I don't think I can use
$(document).ready(function () { ... });
because in my tests that fires before my scripts have been loaded. However, I do not know if this will always be the case. If it will, my callback function is suitable for my DOM-manupilating javascript code.
But if it is possible that my scripts can be loaded before the DOM is ready to be manipulated, I need to find another way.
Thank you for reading!

Check jQuery.holdReady(). If you will try to load external js via getScript then you can easily do that.
Delay the ready event until a custom plugin has loaded:
$.holdReady( true );
$.getScript( "externalScript.js", function() {
$.holdReady( false );
});

Is the DOM always ready when my external scripts have finished loading?
Probably, yes. No.
Dynamically-added script elements load their scripts asynchronously. You're quite correct that you can't use jQuery's ready callback because it looks at when the DOM defined by the main HTML is fully loaded, which may well be before your additional scripts have loaded.
I'd be really, really surprised if the main DOM weren't loaded before your onModuleLoaded callback was called. So probably, yes, it'll be ready. Color me surprised. I ran the experiment, and guess what? It's possible for the script load and callback to happen before the rest of the page has been processed. (This is why I test my assumptions.)
But if you're worried there may be edge cases around it, you could always use ready within your callback. If jQuery has already fired the ready callbacks and you hook another one, jQuery calls it right away.

Related

Is there any advantage to add 'defer' to a new script tag after $(document).ready()?

I have some javascript that is not required for my initial page load. I need to load it based on some condition that will be evaluated client-side.
$(document).ready(function() {
let someCondition = true; // someCondition is dynamic
if (someCondition) {
var element = document.createElement('script');
element.src = 'https://raw.githubusercontent.com/Useless-Garbage-Institute/useless-garbage/master/index.js';
element.defer = true; // does this make a difference?
element.onload = function() {
// do some library dependent stuff here
document.getElementById("loading").textContent = "Loaded";
};
document.body.appendChild(element);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="loading">Loading...</h1>
Does it make a difference (in terms of how browser will treat the script tag), if a new tag created using javascript, after document is ready, has 'defer' attribute or not? I think there is no difference, but how can I say for sure?
I believe I understand how deferred scripts behave when script tag is part of the initial html (as described here). Also, this question is not about whether element.defer=true can be used or not (subject of this question).
No that doesn't make any difference, the defer attribute is ignored in case of "non-parser-inserted" scripts:
<script defer src="data:text/javascript,console.log('inline defer')"></script>
<script>
const script = document.createElement("script");
script.src = "data:text/javascript,console.log('dynamic defer')";
script.defer = true;
document.body.append(script);
</script>
<!-- force delaying of parsing -->
<script src="https://deelay.me/5000/https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Look at your browser's console or pay attention to the logs timestamps to see that the dynamically inserted script actually did execute while we were waiting for the delayed script to be fetched.
There's a difference between adding them to the function and adding directly the CDN ( especially in your case ).
Let's look at the code execution of the above-mentioned code first,
You have added the jquery CDN first ( without defer ) so that loads first.
$(document).ready will be fired once after the complete load of jquery.
There'll be the creation and insertion of a new script tag to the dom.
Download the https://raw.githubusercontent.com/Useless-Garbage-Institute/useless-garbage/master/index.js asynchronously.
Let's look at another approach: adding CDN to the code:
Your DOM will have 2 script tags.
Both will start loading based on the type of load parallelly ( defer async etc ).
Notice you are not waiting for the dom ready event to load the second script.
I suggest adding only the main JS part in a js file and adding it to the CDN. Others can wait load with the delay.
In case you are really needed with a js src, then don't load it the first way since it waits for the complete page load.
I suggest you read and look at web-vitals and SEO for this.
and for your other question, yes you can add defer attribute with element.defer=true to the elements while creating and loading to DOM.
Hope this answer helps you!
Feel free to comment if you get any errors or doubts.
I think the JQuery Arrive lib will solve your case.

Perform animation on a page after page has loaded

I am doing maintenance work for a website. The logo on the home page is supposed to bounce in from left after page has loaded but the animation begins even when the page is still loading.
The code is
$(document).ready(function(){
$('#logo-large').addClass('animated bounceInLeft');
});
The site is using animate.css library
The ready method do not wait for resources to load.
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. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
Reference: https://api.jquery.com/ready/
Use window.load method:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
$(window).on('load', function() {
$('#logo-large').addClass('animated bounceInLeft');
});
Reference: https://api.jquery.com/load-event/
The problem here is that you say "page loaded" but you haven't defined what that means. The animation is, indeed, playing after the DOM has loaded. That's what the $(document).ready method insures. However, any images or asynchronous calls can still trigger after the DOM is ready. So... the REAL question is, do you want to wait til after the images have loaded AND do you have any asynchronous calls that need to be accounted for.
I just wrote this so I'm not 100% sure if it doesn't have any bugs, but this should work for both cases.
jQuery.prototype.pageComplete = function(promises, callback){
if(!callback){
callback = promises;
promises = [];
}
var images = jQuery.Deferred();
var DOMReady = jQuery.Deferred();
var count = this.length;
promises.push(images);
promises.push(DOMReady);
jQuery(document).ready(function(){
DOMReady.resolve();
});
function counter(){
if(--count == 0) images.resolve();
}
this.each(function(image){
var img = new Image();
img.onload = counter;
img.src = image.src;
});
jQuery.when.apply(jQuery, promises).then(callback);
};
You use it like so:
// for just images
$('img').pageComplete(function(){
// code to transition image here
});
// for images and ajax
$('img').pageComplete([
ajax1, // these are all promises created by jQuery.ajax
ajax2,
ajax3
],
function(){
// code to transition image here
});
Try this one, solution should work without jquery
window.onload = function() {
document.getElementById('logo-large').classList.add('animated', 'bounceInLeft');
};
Use The Window Load Function
This will wait until the whole page has loaded before running the animation
jQuery(window).load(function() {
$('#logo-large').addClass('animated bounceInLeft');
});)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

My code gives me an error message: GetElementById() is null or not an object

I have this js code:
var id = document.getElementById("myDiv").getAttribute("data-id");
et="Your Message Here";
el="http://x2.xclicks.net/sc/out.php?s="+id+""
sl=new Array();
sn=new Array();
a="</a>"; af="<a target='_blank'";
function dw(n) {document.write(n,"\n");}
function showLink(n,s,b){
if(!s) {s='anc'}
if(!b) {b=''}
else {b="&b="+b}
ast = af+" class='"+s+"' href='"+el;
n = n-1;
if(sl[n]&&sl[n]!="") {
dw(ast+"&o="+sl[n]+b+"'>"+sn[n]+a)
} else {
dw(ast+b+"'>"+et+a)
}
}
Which I load in my header.php like this:
<script type="text/javascript" src="<? bloginfo('template_url'); ?>/js/trf.js"></script>
The problem is that although this is correct:
var id = document.getElementById("myDiv").getAttribute("data-id");
I get this error:
getElementById() is null or not an object
Ady Ideas why?
Do I need to declare a document ready or something?
Do I need to declare a document ready or something?
Yes, exactly. Before the document is ready (ie all tags are parsed to DOM elements), you won't be able to get elements by id. This would only work for elements above your script tag, which are already parsed. Moving the script inclusion from <head> before the end of </body> would help. Alternatively you'll need to use one of the various DOMContentLoaded or onload events, which unfortunately are not cross-browser supported. I recommend to search for a good snippet or use a library.
Assuming you're loading that script in the <head> of your document, you are trying to get an element by ID when that element is not yet loaded into the DOM.
You will need to wait for your document to be ready (via onDOMContentLoaded, window.onload, or any other way of deferring until rendering is complete) in order to access that element by ID.
I would try wrapping it in a $(document).ready. More than likely you're just trying to access it before the DOM is ready
You're loading the script in the header, which means that the script is being loaded before the rest of the document. Inside the script, you're calling document.getElementById straight away, and since the rest of the document hasn't finished loading the chances are extremely high the element you're after won't exist yet.
You need to delay running that part of the script until the document is fully loaded. Wrap that part of the script in a function, and call it during the body.onload event.
As an example (there are other ways to achieve the same result):
window.document.onload = function(e){
var id = document.getElementById("myDiv").getAttribute("data-id");
// Now you have the id and can do whatever you want with it.
}

Position of window.onload in Javascript

I have a javascript code like this
<script type="text/javascript">
window.onload=myFunction;
</script>
Is there any difference in using the above snippet in the <head></head> tag and just before
</body> tag, as I would like to call my function after the page loads.
basically there's no pratical difference, but I recommend
to place that code at the bottom, since you need to use a script (blocking-rendering tag) it's better put it at the end of the document.
to avoid a destructive assignments like that: writing window.onload=myFunction you destroy other previous assignments to window.onload event (if any) so it's better something like
(function() {
var previousOnLoadIfAny = window.onload;
window.onload = function() {
if (typeof previousOnLoadIfAny === 'function') {
previousOnLoadIfAny();
}
yourfunction();
}
}());
Binding to window.onload will always run your function when the load event fires. This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to the DOMContentLoaded event or use a library like jQuery (e.g. $(function(){ myFunction() });).
The benefit about putting your function at the end of your <body> is that theoretically this means that the rest of your content has already loaded and you don’t need to bind your function to a load event. This sometimes works, but depends on the situation.
No, where you place that will not matter - anywhere in the document and it will trigger when the document and all external resources (images, scripts etc) has loaded.
Because onload triggers after all external resources one often want to use DOMContentLoaded instead which triggers when the HTML DOM is ready. Which will make for a page that is more responsive.

What are the ways to minimize page wait from external javascript callouts?

What tricks can be used to stop javascript callouts to various online services from slowing down page loading?
The obvious solution is to do all the javascript calls at the bottom of the page, but some calls need to happen at the top and in the middle. Another idea that comes to mind is using iframes.
Have you ever had to untangle a site full of externally loading javascript that is so slow that it does not release apache and causes outages on high load? Any tips and tricks?
window onload is a good concept, but the better option is to use jQuery and put your code in a 'document ready' block. This has the same effect, but you don't have to worry about the onload function already having a subscriber.
http://docs.jquery.com/Core/jQuery#callback
$(function(){
// Document is ready
});
OR:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
edit:
Use this pattern to call all your external services. Refactor your external script files to put their ajax calls to external services inside one of these document ready blocks instead of executing inline. Then the only load time will be the time it takes to actually download the script files.
edit2:
You can load scripts after the page has loaded or at any other dom event on the page using built in capability for jQuery.
http://docs.jquery.com/Ajax/jQuery.getScript
jQuery(function($) {
$.getScript("http://www.yourdomain.com/scripts/somescript1.js");
$.getScript("http://www.yourdomain.com/scripts/somescript2.js");
});
Not easy solution. In some cases it is possible to merge the external files into a single unit and compress it in order to minimize HTTP requests and data transfer. But with this approach you need to serve the new javascript file from your host, and that's not always possible.
I can't see iframes solving the problem... Could you please elaborate ?
See articles Serving JavaScript Fast and Faster AJAX Web Services through multiple subdomain calls for a few suggestions.
If you're using a third-party JavaScript framework/toolkit/library, it probably provides a function/method that allows you to execute code once the DOM has fully loaded. The Dojo Toolkit, for example, provides dojo.addOnLoad. Similarly, jQuery provides Events/ready (or its shorthand form, accessible by passing a function directly to the jQuery object).
If you're sticking with plain JavaScript, then the trick is to use the window.onload event handler. While this will ultimately accomplish the same thing, window.onload executes after the page--and everything on it, including images--is completely loaded, whereas the aforementioned libraries detect the first moment the DOM is ready, before images are loaded.
If you need access to the DOM from a script in the head, this would be the preferred alternative to adding scripts to the end of the document, as well.
For example (using window.onload):
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
window.onload = function () {
alert(document.getElementsByTagName("body")[0].className);
};
</script>
<style type="text/css">
.testClass { color: green; background-color: red; }
</style>
</head>
<body class="testClass">
<p>Test Content</p>
</body>
</html>
This would enable you to schedule a certain action to take place once the page has finished loading. To see this effect in action, compare the above script with the following, which blocks the page from loading until you dismiss the modal alert box:
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
alert("Are you seeing a blank page underneath this alert?");
</script>
<style type="text/css">
.testClass { color: green; background-color: red; }
</style>
</head>
<body class="testClass">
<p>Test Content</p>
</body>
</html>
If you've already defined window.onload, or if you're worried you might redefine it and break third party scripts, use this method to append to--rather than redefine--window.onload. (This is a slightly modified version of Simon Willison's addLoadEvent function.)
if (!window.addOnLoad)
{
window.addOnLoad = function (f) {
var o = window.onload;
window.onload = function () {
if (typeof o == "function") o();
f();
}
};
}
The script from the first example, modified to make use of this method:
window.addOnLoad(function () {
alert(document.getElementsByTagName("body")[0].className);
});
Modified to make use of Dojo:
dojo.addOnLoad(function () {
alert(document.getElementsByTagName("body")[0].className);
});
Modified to make use of jQuery:
$(function () {
alert(document.getElementsByTagName("body")[0].className);
});
So, now that you can execute code on page load, you're probably going to want to dynamically load external scripts. Just like the above section, most major frameworks/toolkits/libraries provide a method of doing this.
Or, you can roll your own:
if (!window.addScript)
{
window.addScript = function (src, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
script.type = "text/javascript";
head.appendChild(script);
if (typeof callback == "function") callback();
};
}
window.addOnLoad(function () {
window.addScript("example.js");
});
With Dojo (dojo.io.script.attach):
dojo.addOnLoad(function () {
dojo.require("dojo.io.script");
dojo.io.script.attach("exampleJsId", "example.js");
});
With jQuery (jQuery.getScript):
$(function () {
$.getScript("example.js");
});
If you don't need a particular script ad load time, you can load it later by adding another script element to your page at run time.

Categories

Resources