I'm developing JS that is used in a web framework, and is frequently mixed in with other developers' (often error-prone) jQuery code. Unfortunately errors in their jQuery(document).ready blocks prevent mine from executing. Take the following simple sample:
<script type="text/javascript">
jQuery(document).ready(function() {
nosuchobject.fakemethod(); //intentionally cause major error
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
alert("Hello!"); //never executed
});
</script>
Shouldn't the second ready block execute regardless of what happened in the previous? Is there a "safe" way to run jQuery(document).ready that will run even in the case of previous errors?
EDIT: I have no control/visibility over the error-prone blocks as they're written by other authors and mixed in arbitrarily.
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
jQuery ready() MethodThe ready event occurs when the DOM (document object model) has been loaded. 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. The ready() method specifies what happens when a ready event occurs.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
I haven't tried this code, but it should work (at least, the idea should anyway). Make sure you include it AFTER jquery, but BEFORE any potentially buggy scripts. (Not necessary, see comments.)
var oldReady = jQuery.ready;
jQuery.ready = function(){
try{
return oldReady.apply(this, arguments);
}catch(e){
// handle e ....
}
};
To answer your question, both of the ready
blocks are essentially combined into one given the way jQuery works:
<script type="text/javascript">
jQuery(document).ready(function() {
nosuchobject.fakemethod(); //intentionally cause major error
alert("Hello!"); //never executed
});
</script>
So that's why its not alerting per the error above. I don't believe there is a way to fix this to make every ready
function run regardless of former failures.
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