jQuery $(document).ready () fires twice - javascript

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.

Related

Immediate function in script not being executed

I have a script being loaded on my index.html page. It has dependencies on jQuery, bootstrap.js, & metisMenu.js all of which are being loaded before it. I can't figure out why this script is not being immediately executed.
If I open the chrome console and run the code, it works just fine, I'm also not seeing any errors in console.
index.html
...
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/metisMenu/dist/metisMenu.js"></script>
<script src="scripts/custom/sb-admin.js"></script> //This is the script I'm referring to
</body>
sb-admin.js
$(function() {
$('#side-menu').metisMenu();
});
What am I missing here? I'm almost positive $(function() {...}); is shorthand for document ready in jquery, yes?
This script is for the nav.html view, and on index.html, because I was using <div ng-include="'views/nav.html'"></div> the page had technically loaded and executed my script, even though Angular still was loading the ng-include view.
I moved the script into nav.html and now it seems to be working just fine. Thanks to #zerkms for reminding me to use debugger; which I should have done in the first place O_o
try instead
$(document).ready(function() {
});
;-)
and if you try to do an IIFE (look on google)
do
(function() {
})();

Best way to access external JavaScript file and place contents in div?

So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.

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

javascript function call not working

Inside register.js I have a function called username() and I want to call it from my webpage but the function will not run.
Here is where I include the .js file and call the function:
<head>
<link rel="stylesheet" href="css/base.css" />
<script src="resources/jquery-1.8.1.min.js"></script>
<script src="resources/register.js"></script>
<script type="text/javascript">username();</script>
</head>
This is in the .js file:
function username(){
document.getElementById("username").innerHTML="Username already in use";
}
This is a common mistake from folks just starting out in Javascript. Trouble is, if you don't know what to call it, it is hard to search for the answer.
What is happening: When the <head> element is processed, nothing in the document body exists yet. Your element username doesn't exist, so the getElementById fails.
Solution 1 Move <script type="text/javascript">username();</script> to just before the </body> so everything will be in place.
Solution 2 Use the onload event to run your Javscript after everything else runs with a
<body onload="username()">
(jQuery has its own onload event handling as well.)
You have no element with the id username.
(You might have one lower down in the document, which you haven't shared with us, but since you are calling the function directly (and not in response to an event, such as load) while still in the <head> it won't yet exist.)

Uncaught ReferenceError $ is not defined

I'm very new to JavaScript (just started a few hours ago and trying to get a script working). I went through a few tutorials on W3 and the 'hello world' code works when I paste it directly into my HTML but I'm having a problem with a script (I've had problems with other scripts as well but I am not sure what I'm doing wrong).
I have this code that I want to test in my HTML, I copied the HTML in and it looks the same then I made a file in my static folder called edit.js and copied the JavaScript into it (exactly as shown). It didn't work no errors on the page but when I click it nothing happens. I tried to paste a W3 'hello world' code in and that worked but this script does not.
I tried to inspect the code in Chrome and that's where I see the above error (under the resources tab). I can open the js file using Chrome which makes me think the js file is accessible and pointing correctly but I'm not sure how to get it working. I'm using Jinja2 as my template engine to render the HTML and in my header I have:
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
and in my main template (the one that gets rendered on all pages) I have:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
edit.js:
(even putting it within the script tag directly on the page I want to use it on doesn't work)
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
HTML:
(it's embedded in a larger page)
<head>
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
</head>
... my html code..
<div id="wrapper">
<div id="container">
<div id="storedvalue"><span>Hello</span> [edit]</div>
<div id="altervalue" style="display:none;"><input type="text" name="changevalue" id="changevalue" value="Hello"> [save]</div>
</div>
</div>
I have never been able to successfully run a JavaScript that wasn't on W3 yet. I get the same problem with other scripts even though I see people online saying they work fine for them. Do I need to do anything extra to make this work?
My two questions are:
What am I doing wrong?
Because Javascript seems to just not work when there's a problem, is there a way to get errors or information on what's actually wrong?
I read Uncaught ReferenceError: $ is not defined? and have been trying to figure this out for the last hour and can't see my problem.
First you need to place the jQuery script tag first.
Second, you need to do one of the following things:
Put your code within this function:
$(document).ready(function(){/*CODE HERE*/});
Or like this:
$(function(){
/*CODE HERE*/
});
The DOM needs to be ready before you can use it. Placing your code within anonymous functions that are executed on the ready event of the DOM is how you can do this.
Edit:
$(function(){
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});​
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Script tag for jQuery should come before your custom javascript.
Follow by edit.js
<script type="text/javascript" src="static/edit.js"></script>
Try removing the language attribute..sometimes work for me. It's obsolete now .. i think
You need to include jquery before you can use it.

Categories