-2

I have a gltf model that I am loading into my website using the Babylon 3D Viewer for WordPress plugin, and I would like to defer the script so that it isn't affecting my load time. All of the plugins I found for async/deffering Javascript seem to not apply to 3rd party scripts like the one this plugin imports (from this url: https://cdn.babylonjs.com/viewer/babylon.viewer.js).

Is there any other way I can defer the script?

user15641284
  • 165
  • 1
  • 1
  • 6

1 Answers1

0

One way you might be able to do this is with the script_loader_tag filter. See below:

function mind_defer_scripts( $tag, $handle, $src ) {
    // array of scripts to add defer tag to
    $defer = [
        'https://cdn.babylonjs.com/viewer/babylon.viewer.js'
    ];

    // check if current script should be deferred
    if ( in_array( $src, $defer ) ) {
        return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
    }
    
    return $tag;
} 
add_filter( 'script_loader_tag', 'mind_defer_scripts', 10, 3 );

Note if you know the "handle" you could use that in-place of src like below:

function mind_defer_scripts( $tag, $handle, $src ) {
    // array of scripts to add defer tag to
    $defer = [
        'babylon'
    ];

    // check if current script should be deferred
    if ( in_array( $handle, $defer ) ) {
        return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
    }
    
    return $tag;
} 
add_filter( 'script_loader_tag', 'mind_defer_scripts', 10, 3 );
mikerojas
  • 2,238
  • 1
  • 4
  • 7
  • Thanks, for some reason I'm getting an error when I try to edit my functions.php file (Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.), but when I get that resolved I will give this a try. – user15641284 Jan 11 '22 at 23:52
  • sounds good. let me know how it goes. – mikerojas Jan 12 '22 at 00:38
  • I just managed to add that function to my themes functions.php file, not sure if its working I haven't seen any changes to my Google page speed insights yet. – user15641284 Jan 12 '22 at 22:40
  • do you see the `defer` attribute on the script you wanted? – mikerojas Jan 13 '22 at 15:36
  • Good question, I searched through my front end code and it was still a normal – user15641284 Jan 13 '22 at 16:32