Skip to content

Instantly share code, notes, and snippets.

@kovshenin
Created November 29, 2012 07:27
Show Gist options
  • Save kovshenin/4167367 to your computer and use it in GitHub Desktop.
Save kovshenin/4167367 to your computer and use it in GitHub Desktop.
Lazy load a script enqueued in a shortcode during and AJAX callback? Sure!
<?php
/**
* Plugin Name: My Plugin
*/
class My_Plugin_Test_AJAX_Scripts {
function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );
add_action( 'wp_head', array( $this, 'wp_head' ), 99 );
add_action( 'wp_ajax_nopriv_my_action', array( $this, 'ajax_my_action' ) );
add_action( 'wp_ajax_my_action', array( $this, 'ajax_my_action' ) );
add_shortcode( 'foobar', array( $this, 'foobar' ) );
}
function foobar() {
// Enqueue a script like a regular shortcode would, and hope it late inits in the footer.
wp_enqueue_script( 'foo-script', plugins_url( 'test-ajax-scripts.js', __FILE__ ) );
// Do something.
return 'You say foo. I say bar.';
}
function ajax_my_action() {
global $wp_scripts;
$data = array();
$data['content'] = apply_filters( 'the_content', '[foobar]' );
$data['scripts'] = array();
if ( ! empty( $wp_scripts->queue ) )
foreach ( $wp_scripts->queue as $item )
$data['scripts'][ $item ] = $wp_scripts->registered[ $item ]->src;
echo json_encode( $data );
die();
}
function wp_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
}
function wp_head() {
?>
<script>
jQuery(document).ready(function($){
$.post(ajaxurl, { action: 'my_action' }, function(response) {
for (var handle in response.scripts) {
var src = response.scripts[handle];
// Look for an existing script with that src.
if ( $('script[src^="' + src + '"]').length < 1 ) {
var script = document.createElement('script');
script.src = src;
$('body').append(script);
}
}
}, 'json');
});
</script>
<?php
}
}
new My_Plugin_Test_AJAX_Scripts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment