document.ready like functionality in Javascript? [duplicate] - javascript

This question already has answers here:
How to check if DOM is ready without a framework?
(7 answers)
Closed 1 year ago.
I have a requirement that states to use only plain JavaScript and not jQuery. I need to initialize some variables(using some function) as soon as the DOM is loaded and not when the page has fully loaded. In short it should not wait for the whole page to load. In jQuery it can be very easily done using document.ready() function.
Is it possible to implement it in JavaScript using any function?

a "practical" way is just placing a script block before the end of the document (even is not really equivalent to domready)
...
<script>...</script>
</body>
</html>
or use one of various pure-js implementation of DomReady event, like http://snipplr.com/view/6029/domreadyjs/

It's sometimes achieved like this
<body>
<!--
All your html tags here
....
....
-->
<script type="text/javascript">
//this should execute after the above tags and elements have rendered
</script>
</body>

You can use DOMContentLoaded event if supported:
MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/hh868490.aspx
MDN: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded

if you realy want to wait for "ready event" you can for example use that kind of thing :
(function(w,evt,fn){
if (w.addEventListener){// W3C DOM
w.addEventListener(evt,fn,false);
}
else if (w.attachEvent) { // IE DOM
w.attachEvent("on"+evt, fn);
}
})(window,'load',function(){
// your code here
});
but it's indeed better to simply use a well placed 'script' tag as your code will probably work and start sooner

Related

Plain Javascript: Do I really need wait document ready to attach event to elements? [duplicate]

This question already has answers here:
Is it really necessary to wait for DOM ready to manipulate the DOM?
(4 answers)
Closed 4 years ago.
It seems the following inline code works by putting js right after the tag:
(1)
<div id="xx"></div>
<script>
document.getElementById('xx').addEventListener('click', aFunction);
</script>
It seems there is no need to wait document ready like this:
(2)
<div id="xx"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('xx').addEventListener('click', aFunction);
});
</script>
Will the inline code (1) always work?
Please notice that I made sure <div id="xx"></div> is before the script.
You dont have to but you should. If you dont you will get errors when you try performing actions on elements in the dom when they havent been loaded yet, using document ready just ensures you dont have this issue, one less problem to debug basically.

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

Does "innerHTML" depend on eventhandlers? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
first one:
function change(){
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
}
second one:
document.getElementById("test1").innerHTML="hwllo world";
The first one is working fine. But the second one is not working when the file is loaded.
Javascript and HTML rendering are executed in the sequence they are found in the file. So if you're executing a piece of JS before an HTML element is rendered then the JS code wouldn't work.
This will fail:
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
<div id="test1"></div>
This will work as expected:
<div id="test1"></div>
<script>
document.getElementById("test1").innerHTML="hwllo world";
</script>
Alternatively you can use the various onload and dom ready events to make sure that your script executes after all the HTML have been rendered:
<script>
window.onload = function(){
document.getElementById("test1").innerHTML="hwllo world";
}
</script>
<div id="test1"></div>
And what error is in console? May be you are trying to set innerHTML of not existing node? If you want to manipulate with divs, you have to do it after the page is loaded, so typically call this as body event onLoad:
<script>
function init() {
document.getElementById("test1").innerHTML="hello world";
}
</script>
<body onload="init();">
<div id="test1"></div>
...
As James Allardice said in his comment, the code is probably executed before the DOM is ready. Your code could then fail as the element might not be there. This is a known problem, but there is also a known solution. The most used solution is probably to use jQuery, which has an easy way to allow a function to only be executed after the document is ready. To use this method, first you need to include jQuery as a script reference and then modify your code as follows:
$(document).ready(function() {
document.getElementById("clr").style.backgroundColor="red";
document.getElementById("test1").innerHTML="hwllo world";
});
Now if you are using jQuery anyways, you can also rewrite your code to use jQuery selectors and make it a bit more compact:
$(document).ready(function() {
$("#clr").css("backgroundColor", "red");
$("#test1").html("hwllo world");
});
Both pieces of code are functionally equivalent.

how to call a javascript method soon after page load [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript that executes after page load
how to call a javascript method as soon as page is loaded.
i have a java script which needs to be called soon after the jsp page is loaded, how to achieve this in javascript.
could any one of you help me pelase.
Regards
You can write a code snippet something like this :-
window.onload(function(){
//Your JavaScript here
});
And if using JQuery then
document.ready(function(){
//Your JavaScript Here
});
Or you can have all your JS after all the HTML.
you can even use a function called :--
document.onload(function(){
//Your code Here
});
Last but not the least you could even try out this
<body onload="YourJSMethod();">
<!-- Some html content -->
</body>
you can try
<body onload="someMethod();">
<!-- Some html content -->
</body>
This will call your method as soon as body tag of your page is loaded.
Alternatively you can make use of jquery's document ready function.
$(document).ready(function() {
// your code
});

How can I stop a JavaScript from executing if an element exists?

I have a Firefox addon that injects/executes a jQuery script on every page at sub.example.com. The script doesn't work on one page of the site, because of bad design. Is there any way to stop the script from being executed if a certain element is located on the page?
EDIT: The script I am using has to be executed before the DOM loads. Is there any way to access the HTML file itself and find out if the element exists?
Since jQuery collections are just beefed up arrays, they each have a length property, which tells you how many elements it has matched:
jQuery(document).ready(function($)
{
if ( $('#someElement').length ) return;
// All of your code should go here...
});
Since you're using jQuery, I assume your script is wrapped in a $(document).ready callback, if so:
$(document).ready(function() {
if ($('#breakOnThisElem').length) {
return;
}
});
If your code isn't wrapped in a function like this: change it! :)

Categories