In my code I'm scanning a page to see if we find anything with a class of "coceon" (an image comparison JS lib), if found we then load in the cocoen scripts to then run it.
The code:
/* cocoen image comparison */
if ($('.cocoen').length)
{
var cocoen_js = Promise.resolve($.cachedScript("/includes/jscripts/cocoen/js/cocoen.min.js"));
var cocoean_jquery = Promise.resolve($.cachedScript("/includes/jscripts/cocoen/js/cocoen-jquery.min.js"));
Promise.all([cocoen_js, cocoean_jquery]).then(() => {
$('.cocoen').cocoen();
});
}
The trouble is, sometimes it just fails with the browser console telling me this line:
$('.cocoen').cocoen();
Fails as cocoen is not a function. So sometimes it's not loaded ready when needed. Especially so when doing a hard refresh, something seems to block it? Is there a way to ensure it's actually loaded to then run?
The cache script code if you need to see it too:
jQuery.cachedScript = function( url, options )
{
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};