jQuery $.when - What are the difference between these two elements? One executes instantly, the other works

46 views Asked by At

So imagine we have a product page that initially loads an empty price div, and that div is later populated async after page load.

Using this code we wait until the price appears to have populated, and then execute a function to copy this price across other parts of the page.

This does work, but doesn't do exactly what I want:

// When .price exists, and innerText equals exactly "$10.00", run updateOtherPrices();
when(function () {
            return document.querySelector(".price") != null
            && document.querySelector(".price").innerText === "$10.00";
        })

Really it should work for any price, not just $10.00. So my next logical step was to check the price innerText length is longer than 3.

// When .price exists, and innerText is 3 or more, run updateOtherPrices();
when(function () {
            return document.querySelector(".price") != null
            && document.querySelector(".price").innerText.length >= 2;
        })

The problem is, this second one triggers instantly, and executes before the price even exists. Why is that?

I also haven't been able to find any other way of waiting, other than an exact match on the innerText. Any ideas what else to try?

0

There are 0 answers