JS: How to prevent race condition? - javascript

My task is to improve the performance on an existing WordPress site therefore I installed cache and a race condition started happening.
This is the site. The full code is here, it doesn't fit in the editor, on line 474 there's this function
function loaded() {
var e = $("#content-wrap").attr("data-classes");
if ($("body").attr("class", e), $("#news-slider").length) {
var t = $("#news-slider").attr("data-timer");
$("#news-slider").slick({
dots: !1,
autoplay: !0,
speed: 800,
autoplaySpeed: t,
fade: !0,
cssEase: "linear",
prevArrow: "<span class='prev-slide'><i class='fa fa-angle-left'></i></span>",
nextArrow: "<span class='next-slide'><i class='fa fa-angle-right'></i></span>"
})
}
...
this line
$("#news-slider").slick({
gives slick not defined, sometimes, again it's a race condition. Sometimes an error in another function below it, the problem starts from loaded() function and below. Now I stopped caching the file and the homepage, where the file is loaded, the problem persists.
If I use $(window).load(function() either on the entire file or just this function, the homepage would be messed up, no errors would be visible in console though.
If I use $(document).ready(function() either on the entire file or just this function, the slider on mobile would be messed up, no errors would be visible in console though.
If I set a timer to delay the execution of the script, it wouldn't solve anything.

Related

Why there is an error showing when I try to load the slider in the browser?

I have save the code in slider.js. But when in the browser the slider is not working. It is showing the error
Uncaught ReferenceError: $ is not defined.
But I'm seeing the result of the console.log("ready") inside the $(document).ready(...) handler here:
Jquery code
$( document ).ready(function() {
console.log('ready'); // <===== I'm seeing this
$('.logo-carousel').slick({
slidesToShow: 6,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 1000,
arrows: true,
dots: false,
pauseOnHover: false,
responsive: [{
breakpoint: 768,
settings: {
slidesToShow: 4
}
}, {
breakpoint: 520,
settings: {
slidesToShow: 2
}
}]
});
});
Error
Uncaught ReferenceError: $ is not defined
at Slider.js:1:3
Assuming the code you've shown is at global scope, I can only think of three possibilities:
You've included Sliders.js before including jQuery and the code you've shown in the question.
You're using an iframe and loading Slider.js into it, but jQuery isn't loaded in that iframe; your code is in the main document (or a different iframe) where jQuery is loaded, so it has $ but the iframe with Slider.js doesn't. Remember an iframe is a completely different window from the window containing it. If you want to use jQuery in that iframe, you have to load it in that iframe.
(This seems unlikely) Code running after your code is doing this:
$.noConflict(); // This part is optional but likely to be there
delete $; // This causes the specific error you're seeing
#1 is the most likely scenario, followed by #2; #3 is possible but unlikely.
I won't do an example of #2 because it's awkward with Stack Snippets, but here's an example of #1:
<script><!-- This is Slider.js -->
$(document).on("click", ".slider", function() {
// ...
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
console.log("ready");
});
</script>
And here's an example of #3:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
console.log("ready1");
});
</script>
<script>
$.noConflict(); // This is optional but likely to be there
delete $; // This causes the specific error you're seeing
</script>
<script>
$(document).ready(() => {
console.log("ready2");
});
</script>
Notice we see ready1 but get an error instead of seeing ready2.
If the code following your code only did $.noConflict(), you'd still get an error, but it would be a different one ("$ is not a function). So something is actually removing the $ property from the window object (via delete $ or similar).
Side note: $(document).ready(someFunction) has been deprecated for some time now, details here. Use $(someFunction) instead if you really need to ask jQuery to wait for the DOMContentLoaded event, or better yet use modules (they won't be run until the main parsing of the HTML is completely), or defer on your script tag, or put your script tag at the very end of the document. (But there are times you don't control the script tag, and in those situations $(someFunction) can be useful.)

TYPO3 / OwlSlider PageSpeed Insights - Unable to optimize due to deffer

I have a TYPO3 Page where i need to get a score above 90.
For this in particular i've already set jQuery, OwlCarousel and the initating script to defer.
However, if i keep the Slider away from loading, i get a 97 Score.
If i keep it, it goes down as far as 71.
"Reduce initial response time of the server" comes around if i load it all defer.
As for my understanding, this happens because it loads the HTML and seperatly the JavaScript.
But that will make the Slider load later ofc. because the document gets first loaded.
But if i will load jQuery, OwlCarousel and the init-script without defer the score also will get to 74.
I dont see a solution here, any tipps?
var slider = '.slider-owl-268';
var tnav = true;
var amount = 1;
var dautoplay = false;
amount = parseInt(amount);
var tdots = true;
$(slider).owlCarousel({
items: amount,
lazyLoad:true,
loop: true,
margin: 15,
autoplay: dautoplay,
autoHeight: true,
nav: tnav,
dots: tdots,
fluidSpeed: 1,
responsiveClass: true
});
$( ".owl-prev").html('');
$( ".owl-next").html('');
Edit:
A Tip i might have, atleast Layout Shifting can be eleminated trough setting the Slider visible in min-height with Styles.
It does not solve the defer Problem but at least the user see's no shifting and it gives a few bonus points.
With Cache-TTL and eliminating Layout Shifting i could get a score of 96 without using defer.
I wish i could but atleast i reached my goal. Should i clouse the question #mods?

why my Javascript doesn't load from the beginning

I am a newbie to web development and I am trying to create a portfolio project for practice. My problem is that every time i reload the page it's like the js code load slow and the page shows some elements from the second page and then upload the js script.
$('#slides').superslides({
animation: 'fade',
play: 5000,
pagination: false
});
var typed = new Typed(".typed", {
strings: ["Computer Engineer.", "Data Scientist."],
typeSpeed: 90,
loop: false,
startDelay: 1000,
showCursor: false
});
I upload the code on http://jsfiddle.net/L34re768/5/ also i copy paste the superslides library that i use because the jsfiddle doesn't recognize it. I like to mention that this is not my first project that happen something like that, it happen again with other library of js. Any help please.

bxSlider reloadSlider() is undefined after page load

I'm working on an intime upload+refresh gallery (AJAX and jQuery based)
application.
I can upload multiple images with drag & drop and after uploading. I have to see how will look like the new gallery with the uploaded elements, which is in a bxslider based carousel (without page reload). I've done this successfully with the upload-refresh part. However when refreshing the slides the bxslider attributes from configuration are being lost.
When I want to use the reloadSlider() function I see the following error in Chrome console:
Cannot read property 'reloadSlider' of undefined
$(document).ready(function() {
$('.gallery_output').bxSlider({
slideWidth: 222,
minSlides: 1,
maxSlides: 5,
pager: false,
slideMargin: 0
});
});
function refresh_slider() {
var sliderToRefresh = $('.gallery_output').bxSlider({
auto: true,
controls: true
});
sliderToRefresh.reloadSlider();
}
UPDATE:
I added a button to trigger the event, but got the same error.
$('#refresh').click(function(){
var sliderToRefresh;
sliderToRefresh = $('.gallery_output').bxSlider({
auto: true,
controls: true
});
sliderToRefresh.reloadSlider();
});
Overall I just want to reload the bxSlider with a triggered function, without page reload. Any ideas why the reloadSlider() doesn't work?
You're defining the bxSlider in .gallery_output then trying to access it on #gallery_output :)

How can I switch slides automatically in SlideJS from SlidesJS.com?

I am working on getting SlideJS running, and have some aspects of presentation and behavior in order.
One thing I haven't yet managed is to get it to automatically slide, or transition, from one slide to the next.
The code that is getting the reported error is line 67 in SlideJS's main plugin file, at the last line besides the closing brace below; my copy is at https://cjshayward.com/wp-content/Slides-SlidesJS-3/source/jquery.slides.js:
if (typeof TouchEvent !== "undefined") {
$.data(this, "touch", true);
this.options.effect.slide.speed = this.options.effect.slide.speed / 2;
}
Commenting out the assignment, with my invocation, suppresses the reported error, but I think the code may want more information than this line which appears to merely halve an existing setting. I can assign, without immediate reported error,
this.options.effect['qwerty'] = 'qwerty';
But I get a similar error (i.e. setting a property of undefined), if I have as much as:
this.options.effect.slide['qwerty'] = 'qwerty';
I've tried a number of configuration options, and I can see the manual circles to click to move between slides, but have not yet managed to get an automatic transition (the plugin supports slide or fade options; I want the 'slide' effect). My present options target is:
<script>// <![CDATA[
jQuery(function(){
jQuery('#slides').slidesjs({
slide:
{
speed: 200
},
interval: 2000,
active: true,
auto: true,
effect: 'slide',
height: 528,
interval: 5000,
pauseOnHover: true,
restartDelay: 2500,
swap: false,
width: 940
});
});
// ]]></script>
In view-source:http://www.slidesjs.com/, there are multiple sample invocatiosn, but the only invocation I see after slidejs.min.js's inclusion (the last script loaded from a URL) is:
<script>
$(function() {
$('#slides').slidesjs({
width: 940,
height: 350,
navigation: false
});
});
</script>
Thanks,
Have look at:-
https://jsfiddle.net/5x2tqdsv/
You need to fix your html and also remove the following line:-
effect: 'slide',
There were two issues.
One was that the HTML needed fixing.
The other was that the options were being presented, flat, where the source to http://www.slidesjs.com/examples/playing/ has:
$(function() {
$('#slides').slidesjs({
width: 940,
height: 528,
play: {
active: true,
auto: true,
interval: 4000,
swap: true,
pauseOnHover: true,
restartDelay: 2500
}
});
});
I presently have everything I want, besides the data initially displayed all at once before being Hijaxed (I should be able to address that several ways, and it's not my concern). Besides the HTML issue, there was another issue I had in that I was trying to use a flat dictionary to specify options when I needed to have one option/key (play) have its own dictionary as the value instead of e.g. a number or boolean as its value the way most other options appear to.
The updated JSfiddle I'm working from now is https://jsfiddle.net/ydvtynjL/

Categories

Resources