如何初始化使用$ .getScript加载的jQuery插件

时间:2015-03-06 19:11:36

标签: jquery plugins magnific-popup getscript

我正在检查jQuery插件(magnific popup)脚本是否已经加载到DOM中,如果它不是,那么我想加载它:

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

现在通常我会像这样初始化大胆的弹出窗口:

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

但这不起作用。如何初始化插件并将其应用于我页面上的元素?

2 个答案:

答案 0 :(得分:1)

您希望整合这些想法:

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);
        });         
    }
}

在确定之后的某个时刻:

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

当然可以进行变化,例如参数化插入的元素。

如果$('#foo')还不存在,那么它当然不会起作用。如果选择器结果集为空,jQuery很乐意不做任何事情。使用调试来确定它是否为空。如有必要,请在图片加载后将loadPopup移至,可能在ajax success回调中。

答案 1 :(得分:1)

试试这个:

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


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

         });
    });         
}

这应该有效,因为$.getScript是一个异步调用,并且它在complete回调中你可以预期已经成功加载了获取的脚本。

最初使用它的方式,代码的$('.gallery-img').magnificPopup({ });部分可能在完全获取插件脚本之前运行

注意:A"坏"让原始代码运行的替代方法可能是:

SetTimeout(function(){
   $('.gallery-img').magnificPopup({ });
}, 2000);

" 2000"是你给予的任意2秒(希望在它完成之前调用ajax)。现在,我们知道您无法保证它确实已经完成。因此,坚持第一个选择。

修改

我怀疑当插件确实已经加载时,我的初始代码建议将无效。所以我正在修改:

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

        doPopup('.gallery-img');

    });         
}


function doPupup(selector){
        $(selector).magnificPopup({
          type: 'image',
         gallery: {
            enabled: true
          }

         });
}