Load a jquery event only after the preloader ends - javascript

My website is : https://365arts.me/
So it loads about 16mbs of pics(Yes I know, I'm stupid. I'll try to change it very soon, also if someone could tell me a way to reduce size of do something else(like dynamic loading only when needed, if something like that exists) I'd be very grateful).
I added a preloader for it using:
[html]:
<div class="spinner-wrapper">
<div class="spinner">
<div class="dot1"></div>
<div class="dot2"></div>
</div>
</div>
and corresponging [jquery]:
<script>
$(document).ready(function() {
//Preloader
$(window).on("load", function() {
preloaderFadeOutTime = 500;
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
});</script>
this works well but the problem is I have a javascript code that comes and says Hi! but it runs only for 2.8 seconds. So if loading takes up more than that, It doesnt show up. Can someone please tell me how to make sure that it loads only exactly after loading is completed.
Thanks a ton.
Code for my website:
https://github.com/richidubey/365-Days-Of-Art/blob/master/index.html

this may work
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
if you are happy with pure javascript

My first suggestion is to just get rid of the "Hi!" message since you already have a splash page in the form of the loader. But if you really want that second splash page, you can use the JQuery when() method:
$(window).on("load", function() {
$.when($('.spinner-wrapper').fadeOut(500)).then(displaySplashPage);
});
This assumes that displaySplashPage() is your function for showing the "Hi!" message.
You don't need $(document).ready() and window.on("load") here. Document ready waits for the HTML to be built, then applies event listeners/functions/etc to the structure. Window onload waits for everything to get loaded, then fires. In your case, you're trying to wait for all your pictures to load, so you only need onload.
You might need to have a container around all your main content set to opacity: 0 that switches to opacity: 1 as part of displaySplashPage(). That would prevent things from leaking through as you do the .fadeOut() on the loader.

JavaScript version - run js code when everything is loaded + rendered
window.onload = function() {
alert("page is loaded and rendered");
};
jQuery version (if you need it instead pure JS)
$(window).on('load', function() {
alert("page is loaded and rendered");
});
You can try this:
<script>
// Preloader
$(window).on("load", function() {
fadeOutTime = 500;
sayHelloDuration = 5000;
function hideSayHello() {
var sayHello = $('.say-hello');
sayHello.fadeOut(fadeOutTime);
}
function hidePreloader() {
var preloader = $('.spinner-wrapper');
preloader.fadeOut(fadeOutTime);
setTimeout(function() {
hideSayHello();
}, sayHelloDuration);
}
hidePreloader();
});
</script>
Also, remove the code from lines 83 ~ 87:
<script>
$(document).ready(function() {
$('.say-hello').delay(2800).fadeOut('slow');
});
</script>
About your website performance, you can improve a lot of things right now:
Use smaller thumbnail images on your front page, don't load FULL SIZE images at once. "work-showcase" section is really heavy without real necessity.
Try to incorporate src-set and smaller images for small screens, larger/heavier images for bigger screens. All modern browsers support it, and it will improve performance/loading speed.
Try to lazyload your big images, e.g. only when users scroll down to them, not before. It may take some work to integrate it with your image viewer, but it will additionally speed things up on initial load. My favorite library for this is this one: https://github.com/aFarkas/lazysizes but, you may find something else...
Unrelated to your original question, I have noticed that you have a bug in your HTML - see this screenshot. What kind of code editor do you use? Instead of empty space it apparently inserts invisible dots symbols which are not good. Actually, it's not the invisible dot (that's my editor's space indentation symbol), it's caused by 2 long dash (instead of short dash or minus) in your code after opening html comment tag:

Related

start script as soon as the page opens

I have a jquery script that changes an element to fixed when the page is scrolled.
The problem is that the script won't work until the page is fully loaded, and it can take some time
Is there a way to start the script as soon as the user enters the page, without having to wait until it finishes loading ?
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var menuOffset = $('#ribbonmenu')[0].offsetTop;
$(document).bind('ready scroll', function() {
var docScroll = $(document).scrollTop();
if (docScroll >= menuOffset) {
$('#ribbonmenu').addClass('fixed');
} else {
$('#ribbonmenu').removeClass('fixed');
}
});
});//]]>
</script>
Yeah, put it outside:
$(window).load(function() {
That will answer your question about wanting your script to run instantly, however there are issues beyond just moving it outside the load function.
As Marc B said, your script which calls upon an HTML element will not run if it is outside your load function because for a very, very, small time period the HTML hasn't loaded and your script will not see your HTML.
This will cause an error thus making your script not work as intended. Therefore you should keep it inside the load function and instead look for alternative ways to speed up your server/script.
Rather than using $(window).load(
you could try using $( document ).ready(.
It will load sooner, but as others have mentioned, there isn't a way to get it to load instantaneously and still work. This is because future elements will not have loaded yet.

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 infinite-scroll Not Triggering

I'm making a simple little website to apply a different formatting style to Reddit posts, I'm trying to add the infinite-scroll jQuery plugin but it doesn't do anything. I tried following the (very simple) instructions on the infinite-scroll page and when it didn't do anything I thought I must have entered something wrongly, but then I just copy/pasted the code from the Masonry/Infinite-Scroll example and it still didn't work. Masonry is working perfectly (finally) but I just can't figure out what is wrong with infinite-scroll. I understand the basics of jQuery and JavaScript, but obviously not as much as most of you people, so could you please help me out and let me know what is wrong? My site is live at reddit.ymindustries.com.
Thanks heaps, you guys have rarely failed me so far.
YM
EDIT: If there aren't enough images to fill up the page on the homepage, visit reddit.ymindustries.com/r/aww for more images.
EDIT 2: I believe I located the issue, it is described here: https://github.com/paulirish/infinite-scroll/issues/5
Now to figure out a fix...
EDIT 3: Added a little bit of a hack in to make it sort of work, but it just seems to loop the second page endlessly now. Hmm...
I think your problem is actually css. Make your page longer that client area height. add more images to $container
Point is, botom edge of your $container need to pass bottom of window so scroll event fires so infinite scroll can react on this event and calculate weather or not edge is reached
BTW, in same cases, for instance, when I shrink my window, the example you set is working.
=== UPDATE ===
I found some time to play with infinitescroll and here is final working script, just set pathParse method in your script
$(function () {
var $container = $('#itemContainer');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector:'.item'
});
});
$container.infinitescroll({
navSelector:'.navigation', // selector for the paged navigation
nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
itemSelector:'.item', // selector for all items you'll retrieve
bufferPx:40,
debug:true,
columnWidth:function (containerWidth) {
return containerWidth / 5;
},
loading:{
finishedMsg:'No more pages to load.',
img:'http://i.imgur.com/6RMhx.gif'
},
pathParse: function(path,page){
return $(this.nextSelector).attr("href");
}
},
// trigger Masonry as a callback
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}
);
});
Now, since your next link will not update by it self (http://reddit.ymindustries.com/?after=t3_yh4av), you need to change the callback to pull out last element from ajax response and change next link... could be something like this
function (newElements) {
// hide new items while they are loading
var $newElems = $(newElements).css({ opacity:0 });
// ensure that images load before adding to masonry layout
// ======> if query parameter after=... is caring filename then do this
var lastImageUrl= $newElements[$newElements.length-1].attr("src");
var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
$("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);
$newElems.imagesLoaded(function () {
// show elems now they're ready
$newElems.animate({ opacity:1 });
$container.masonry('appended', $newElems, true);
});
//console.log("test (never fired :( )");
}
You also need to take care of wich version of infinite-scroll your using since if you use the ones that comes with masonry/isotope (version 2.0b2.110713), both need a little hack in order to call the function and not use the predefined array:
//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);
This is already fixed in the newer versions of infinite-scroll
I had the same problem with jQuery's "infinitescroll" and Masonry. You might just solve this by giving your page more initial items so that the plugin's scrolling detection kicks in.
In WordPress this is under the "Reading" settings. By default WordPress only opens 10 items at a time. You could increase that number to 100/page to be more sure the window will be full initially. I had some code here that was just horrible, turns out I just needed longer pages, not more code.
So it's difficult to test these plugins on large displays if you don't have enough images. Maybe the solution is to scale the images larger on large displays so you're more sure about getting your content below the fold.
If you think someone might get to your website with a really huge display, I'm not sure what the answer is other than showing more items/page and maybe adding $('#masonry').infinitescroll('retrieve'); to your footer to load an extra page just in case.

jquery causing “white” on load

I've searched this a bit on the forum, and can't seem to figure out how to fix the common issue of white flashing when a new page loads.
I've tried Chris Coyer's example of placing this above my other javascript:
// Prevent variables from being global
(function () {
/*
1. Inject CSS which makes iframe invisible
*/
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] ||
document.getElementsByTagName('script')[0];
div.innerHTML = '­<style> iframe { visibility: hidden; } </style>';
ref.parentNode.insertBefore(div, ref);
/*
2. When window loads, remove that CSS,
making iframe visible again
*/
window.onload = function() {
div.parentNode.removeChild(div);
}
})();
but, still flashing. I'm a noob to javascript, so I'm not really sure what I'm doing wrong.
The page that is the worst is: http://thegoodgirlsnyc.com/test/new/index3_7.php
If you're using Jquery try wrapping your function with:
$(document).ready(function(){
/* Code goes here */
});
This will execute your code when the document is ready (fully loaded)
The problem is that you're executing tasks throughout the pageload. You're getting the flashing because code is being run in-time with page load.
You need to abstract the running of the code behind a unified point. This is where things like $(document).ready() are nice from jQuery. It happens upon DOM completion, but before window load completion. This means it happens before visual, which prevents screen flash Javascriptiong.
It seems like you're worried about the global namespace:
jQuery( function($){
$('iframe').hide();
$(document).ready( function(){
$('iframe').show();
});
});
This is an easy solution that alleviates the namespacing issue, and you won't have to refactor current code. So my answer is two parts:
Use jQuery.
Use namespacing.
If you still get screen flashing using the above, you need to set the display to none in the stylesheet for the iframe element.

Need help with Cross Browser Inconsistencies in overlay

RESOLVED
I found the issue and am sorry to say it is quite idiotic. On some pages there was an extra closing bracket after the script type=javascript. Apparently Chrome and Firefox ignore the issue but Safari and IE threw up display errors. Thank you to everybody for the excellent support and guidance on the matter. of note, i decided to go with the .show() method as it seemed most logical.
I have the following javascript snippet at the top of my page which validates 2 fields within a login form:
<script type="text/javascript">
$(function() {
$('#submit').click(function () {
$('#login_form span').hide();
if ($("input#user").val() == "") {
$("span#user").show();
$("input#user").focus();
return false;
}
if ($("input#pw").val() == "") {
$("span#pw").show();
$("input#pw").focus();
return false;
}
var overlay = $('<div id="overlay">');
$('body').append(overlay);
});
});
</script>
When a form is submitted (submit is clicked) the function is run which checks to make sure the 2 fields: pw and user have some content. If they do, it opens an overlay script to cover the screen. The function above sits at the top of my screen (in the head)
The CSS for the overlay is:
#overlay { background:#000 url(../images/loader.gif) center no-repeat; opacity:0.5; filter:alpha(opacity = 50); width:100%; height:100%; position:absolute; top:0; left:0; z-index:1000; }
In Chrome:
The function works well but the 'loading' image within the overlay does not show.
In Firefox:
Nearly the same as Chrome but the loading image DOES work if the javascript call is made at the bottom of the page.
In IE:
if the function stays in the head, my page is completely blank (though no server errors). Once I move to the bottom of the page, the loading image appears randomly and if it does, it is VERY slow in its animation.
perhaps I am doing something wrong but trying to build for all three browsers on something this simple is making me bonkers.
Any suggestions for improvement?
Thanks ahead of time.
UPDATE
First off thank you all for your suggestions so far. I have tried and number and get various results from each (as well as different results when run locally versus on our apache server).
One page in particular that seems to be of fury is this one:
https://www.nacdbenefits.com/myadmin/password-reset
In IE, the page just opens to a grey screen. I have updated the code to imbed the div id in the page itself and simply 'show' on a submit but apparently something else is catching a long the way.
UPDATE 2
Something else must be causing this to malfunction. When i strip the code even to:
<script type="text/javascript">
$(function() {
});
</script>
unless I move the code to the bottom of the page, IE just shows a dark screen with nothing there (no server errors again and no JS errors at page bottom).
I would have the overlay already existant in the page's HTML but hidden (display: none;), so that the background image is preloaded. Then, once my button is clicked, I would .show() it.
I think your code has a bug. I'm suprised Firefox manages to make something out of it. According to .append() you should pass it a string or an element. You're attempting to pass it a jQuery selector result (and a broken one at that). Remember, in jQuery $() is a function call! Compare your code (condensed):
$('body').append($('<div id="overlay">'));
with this (no $() call):
$('body').append('<div id="overlay" />');
or this (note closing the div tag):
$('body').append($('<div id="overlay" />'));
Have you considered having the overlay as part of your page's code, but simply display: none by default, and then simply .show()ing it when you want it to appear?
The head/bottom-of-page inconsistency can be fixed by running your binding when the DOM is ready, like this:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
// code omitted for brevity
});
});
</script>

Categories

Resources