Support

Account

Home Forums Front-end Issues How to wait until content is loaded before running JS?

Solving

How to wait until content is loaded before running JS?

  • I’m trying to use custom Javascript to create a slider and I need to wait until the content of the fields has loaded before I run my JS. But it seems like sometimes it’s running before the content is there.

    I’m enqueuing the script in the functions.php file like this:

    function my_head_input()
    {
        wp_enqueue_script( 'stories-slider', get_template_directory_uri() . '/js/slider.js', array('jquery') );
    	
    }
    
    add_action('acf/input/admin_head', 'my_head_input');

    Should I enqueue the script differently?

  • Are you useing jQuery? Or does the slider script use jQuery?

    Where you need to add the code to wait for the content to load is in the JS that you’r enqueuing. If you’re using jQuery then you’d do something like this.

    
    jQuery(document).ready(function($) {
      // your code here
    });
    

    edit: of course you’re using jQuery, your script depends on jQuery and I should have seen that in what you posted, excuse the dumb question.

  • Thanks for responding. Yes, all of my code is already wrapped in a document ready function as you suggested. For some reason, the content is still not always loaded when my script runs. Is there a way to ensure that the ACF plugin is loaded before my script?

  • So, I’m a little confused. What exactly is in the slider? How are the fields being loaded into the page?

  • I’m just pulling in content like images and text into the php page template. For example:

    <li class="slide"">
    										<img src="<?php the_sub_field('client_img'); ?>">
    										<div class="copy">
    											<p><?php the_sub_field('client_testimonial'); ?></p>
    											<div class="author">- <span class="name"><?php the_sub_field('client_name'); ?></span>, <span class="title"><?php the_sub_field('client_title'); ?></span>
    											</div>
    										</div>
    </li>

    That part is working fine. It’s just that at the time that my JS runs, it only sees the HTML and not the actual field values.

  • If the output is generated by PHP then the doc ready function should not be happening before the page is loaded. Unless the script for the slider needs the images to actually be loaded before it can run, but if that’s causing it then I’d be surprised. Maybe there’s a javascript error that’s causing a problem?

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.