Search code examples
jquerypluginsmagnific-popupgetscript

How to initialize jQuery plugin loaded using $.getScript


I am checking if a jQuery plugin (magnific popup) script is already loaded into the DOM, if it isn't then I want to load it:

    if(typeof $.fn.magnificPopup !== 'undefined'){
        console.log('Plugin exists');
    }else{
        $.getScript('vendor/jquery.magnific-popup.min.js', function(){
            console.log('Script loaded.');
        });         
    }

Now normally I would initialize magnific popup like this:

    $('.gallery-img').magnificPopup({
        type: 'image',
        gallery: {
            enabled: true
        }
    });

But this isn't working. How do I initialize the plugin and apply it to elements on my page?


Solution

  • You want to integrate the ideas:

    function loadPopup(popupParams) {
        if ( typeof $.fn.magnificPopup !== 'undefined' ) {
            console.log('Plugin exists');
            $('#foo').magnificPopup(popupParams);
        }
        else {
            // Watch out! Relative URLs not recommended. Start with a '/' and traverse.
            $.getScript('vendor/jquery.magnific-popup.min.js', function() {
                console.log('Script loaded.');
                $('#foo').magnificPopup(popupParams);
            });         
        }
    }
    

    And at some point after that's been defined:

    loadPopup({type: 'image', gallery: { enabled: true } });
    

    Variations are of course possible, such as parameterizing the element that gets inserted into.

    If $('#foo') doesn't exist yet, then of course it won't work. jQuery is happy to do nothing if the selector result set is empty. Use debugging to determine if it's empty or not. If necessary, move the loadPopup to after the image has loaded, likely in the ajax success callback.