document.ready not executing on every load - javascript

I have a strange problem. I have a jQuery document.ready function executing some script on the page. When I was testing it through opening the file with firefox/opera it worked. When I uploaded it to the server (I tried both my home apache and my shared hosting) it only works once in 10 loads maybe.
What could be the problem?
Thanks beforehand
Edit:
Here is the code. It configures the correct size of side panels according to central panel.
<script type="text/javascript">
$(document).ready(function(){
// Get natural heights
var cHeight = $("#content").height();
var nHeight = $("#left").height() - $("#footer").height() - $("#header").height() - 10;
// Assign maximum height to all columns
$("#leftcontent").height(nHeight);
$("#rightcontent").height(nHeight);
$("#left").height(cHeight);
$("#right").height(cHeight);
});
</script>

Check that you have no JS syntax errors first (firebug or simply the error console).
If not have you considered just putting a simple alert in the ready function. If that still fails you know its something to do with the JQuery library itself (unlikely).
If you consistently get alerts you know its a problem with your own code. Further help with that will require sight of your code.

Related

ERROR: Execution of script failed! $ is not defined

I've used my script on Tampermonkey (Firefox) for 6 month.
At now I have this error, script work partially, not all time.
I don't know why.
I have tries various suggestions about jQuery, doesn't work
Top of my script:
(function() {
'use strict';
function RPP(){
RedeemRPProduct('fp_bonus_100');
}
var body = $('body'); //I think error is here..
var points = {};
At now script works some times. When it doesn't works appear in console this error:
ERROR: Execution of script 'script-name' failed! $ is not defined
What's happened?
Thanks
I think the cause is that the website administrators removed jQuery from their code. With modern JS, it's mostly obsolete for things like selectors. I recommend simply removing jQuery references from your script and use normal DOM API:
To access body:
document.body
To find an element using selector:
document.querySelector("div#my_div")
Alternatively you could include jQuery in your script using #require.
I see your problem is solved, but leaving this here for others with the same error...
I'm also using Firefox, and my Tampermonkey was 1 year old (I forgot that I disabled the addon's auto updating). It worked fine, I never had the problem you described. Till a couple of days ago when I updated to the new version, and my userscripts stopped loading 10% of the times (got the mentioned error message in console).
Newer Tampermonkey-s are much faster than older versions, loading the userscripts earlier, sometimes before the jQuery library script of the original site is loaded, even if you are using // #run-at document-end.
How I fixed: wrapped my whole userscript content into 1 function, which is called only when the jQuery script is 100% loaded, using a checker function.
Add the next line to the top of your script, right after the Header:
function runScript() {
Add the next lines to the bottom of your script (to the end):
};
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
$(runScript);
clearInterval(waitForJQuery);
}
}, 100);
You're referencing jQuery (via the $) before it has loaded into the page.
It is working sometimes as I'm guessing on some occasions jQuery manages to load before you make your call...but sometimes it doesn't and you see the error.
Try this:
<script src="...your jquery reference..."/> <!-- at the top of your page -->
<!-- at the bottom of the page -->
<script>
var body;
var points = {};
document.addEventListener("DOMContentLoaded", function() {
body = $(body); //it won't try and use jQuery until the doc is ready
//...other script stuff...
});
</script>

Prevent inline scripts loading until Jquery has been loaded

Ok, I have a Jquery script, its function is to determine the width of the window, onload. If the width is greater than 642px it calls .load() to load an image slider. The reason for this is mobile devices will neither be served the images or js required for the slider.
This worked fine when jquery was loaded in the head. Upon moving to the footer its breaking. The code is included from the index.php. Could this be whats causing it? I would have thought once php built the page jquery parsed the content?
It appears the code is parsed before the jquery is loaded. Can anyone suggest a way to get round this please?
I have thought of creating the code as pure JS or using a delayed load, but I cant seem to figure out how to get it working.
There must be much better solutions? I feel like I’m missing something very obvious..
contents of the included script:
<script type="text/javascript">
$(window).bind("load", function() {
// code here
$(window).width(); // returns width of browser viewport
var width = $(window).width();
if (width >= 642) {
$('.slider-content').load("templates/include/slider.php", function () {
$('.slider-content').show(200);
});
}
else {
//alert('small')
}
});
</script>
Thanks,
Adam
In some environments, you must use jQuery() instead of $(). See this question.
Other than that, your problem might have to do with the document not being complete yet or binding to an event that has already passed. Try this instead:
jQuery(document).ready( function($) {
// Your code goes here. (You can safely use the $() function inside here.)
});

JQuery not running correctly on document.ready();

I have placed this inside of my jsp file:
<script>
jQuery( document ).ready(function() {
jQuery('#resrcTypesTree').height(jQuery('.secondColumn').innerHeight() - 10);
});
</script>
If I run this directly in Chrome's console, it works with no problems. If I load the page, the #resrcTypesTree id is set to 10px (a css default). I cannot figure this out as to why it appears to not be setting the height of the resrcTypesTree to the secondColumn's height. Is there something else that I am missing? I could put in a pause to check the page after a unit of time goes past, I just feel that is hacky.
The $ for jQuery is being overridden by another library in the project that is why I called jQuery instead of the '$'.
Can someone point me in the right direction please? Thank you in advance!
RR
Depending content you are targeting but as a simple fix, you should wait all content to be loaded:
jQuery(window).on('load',function () {
jQuery('#resrcTypesTree').height(jQuery('.secondColumn').innerHeight() - 10);
});
This ended up being an ajax issue. I had to write a mediator function since there are more than one ajax call being ran. 95% of the time the re-size works once put into the ajax script, however the 5% of the time, the secondary ajax call would get done first, causing the page not to re-size the gradient correctly.

Counting the number div loaded from external php file

I have two php files, child.php and parent.php. Child.php generates div. Now, the parent.php calls child.php to be loaded in <div id='divContainer'>. Now, I need to count the div inside the divContainer. Is it possible?
I tried something like this:
$(document).ready(function () {
var total_record = $('#divContainer > div').length;
alert(total_record);
});
But it's not working. Even an empty alert is not popping out.
Can someone here, help me on this? THank you!
There's a syntax error:
)};
Should be:
});
Often if you are not getting any output/result at all when expected, it is down to a syntax error which will cause the browser to be unable to parse and execute the code. For future debugging, use the error console as this normally points out any errors with a decent description of the problem.

Code won't execute in $(document).ready but will in developer console

I have some code wrapped in $(document).ready(function(){ /*code*/ });, and all of it works fine, except for one line. The code above it works fine, the code below it works fine, I'm not getting any errors in my console.
$('.main-right.category').height( $('.footer').height() + $('.main-right.category').height() );
That doesn't fire. However, if I paste that exactly in the developer console and press enter after the page has loaded, it works. All of the elements exist at page load (meaning none are built dynamically via javascript). Same result in chrome, firefox, IE.
Any ideas?
edit: I should add that my css is loaded before my javascript, and I've done other CSS related tweaks in this same javascript file that have worked fine.
Also, if I console.log $('.main-right.category').height() and $('.footer').height() right above that line of code, they both give non-zero integer values like I'd expect.
The ready event fires when the DOM is ready to work with. It differs from the load event which fires when all assets (css, javascript, images, ...) are all loaded.
I guess that when you code runs, the elements you're trying to get the height does have an height calculated already so it seems nothing happens.
When you executed your code in the console, everything is loaded so the behavior is the one expected.
To bind to the load event, check the method .load().
$(document).ready fires when the DOM-structure is full available, at this time the rendering ususally isn't finished, so the dimensions of the elements may be unknown and height() will return wrong values.
Use $(window).load() instead.
i usually set height with:
var height = $('.footer').height() + $('.main-right.category').height();
$('.main-right.category').css('height',height+'px');
You should use the console to debug the selectors and view the heights of the elements;
$(document).ready(function() {
var $footer = $('.footer');
var $category = ('.main-right.category');
console.log($category, $footer);
console.log($category.height(), $footer.height());
console.log('New height =', ($category.height() + $footer.height()));
});

Categories

Resources