In the past, I have used $(window).onload to run a block of code after other scripts have loaded. In this case I don't have the ability to change the loading order of the JS files and the code that I am concerned with needs to manipulate DOM nodes that are dynamically inserted by another JS file that is loaded further down the page. Both scripts are located near the bottom of the document. Does anyone have any suggestions for this scenario?
jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.
JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.
The purpose of using jQuery is to make the javascript code easy to execute on the website, as jQuery wraps the many lines of code written in javascript, into a method that can be called with a single line of code. For this reason, a lot of common tasks that require javascript can be taken by jQuery.
The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.
If you know what elements to expect, you can use setInterval
to poll the DOM to see when they've been inserted. For example, this is how you could poll for an element with ID foo
:
$(window).load(function ()
{
var i = setInterval(function ()
{
if ($('#foo').length)
{
clearInterval(i);
// safe to execute your code here
}
}, 100);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With