Reputation: 3628
I got this JS to fade in the wrapper when the page has loaded:
$(window).on('load', function(){
$(".wrapper").fadeIn();
...
});
It's working for one single page, but not for any other page.
There, the wrapper just doesn't fade in.
I tried a console.log
but that didn't work aswell, so the function isn't executing at all.
The JS file is loaded via a PHP-include:
<?php
include 'website/inc/head.php';
?>
And the head.php
loads the main.js
. That's the same for every page. But it doesn't execute the function on all of the pages except one.
By the way, I am using $(window).on('load', function(){...});
, because I got a a.indexOf is not a function
error when using $(window).load(function(){...});
Upvotes: 1
Views: 654
Reputation: 90068
You have the following structure in main.js
:
$(document).ready(function(){
// this code is applied when `document.ready` fires`
$(window).on('load', function(){
// this code is applied when `window.load` fires
// if it was bound before `window.load` fired
});
})
The code inside $(document).ready
is not applied when your main.js
is parsed, but when ready
fires on $(document)
.
$(document).ready()
fires when DOM has finished building.
(Basically wen the browser meets the </html>
tag).
$(window).load()
fires when all resources (scripts, styles, images, ...) have finished loading.
When document.ready
event fires, the code inside that function is applied, while the browser continues to load resources.
If the page is very light and the connection to the server very fast, window.load
will fire before the browser finished applying the code from $(document)ready(...)
. So it might bind the listener on window.load
after window.load
already fired.
The solution is to bind the listener on window.load
when main.js
is parsed, not when document.ready
fires:
$(document).ready(function(){
// this code is applied when `document.ready` fires`
})
$(window).on('load', function(){
// this code is applied when `window.load` fires
// and now you can be sure it has been bound before `window.load`
});
Upvotes: 1