通过Modernizr加载jQuery后运行自定义代码 [英] Run custom code after jQuery has been loaded via Modernizr

查看:119
本文介绍了通过Modernizr加载jQuery后运行自定义代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个新网站,并决定第一次使用Modernizr。我很确定它是如何工作的一般要点,但我正在寻找关于加载jQuery然后运行jQuery代码的最佳实践的一些建议。

I'm in the process of developing a new site and have decided to use Modernizr for the first time. I'm fairly sure of the general gist of how it works however, I was looking for some advice regarding the best practise when it comes to loading jQuery and then running jQuery code.

我目前有以下内容作为我页面上的最后一项加载:

I currently have the following that is loaded as the last item on my page:

Modernizr.load([
    {
        load: '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
        complete: function(){
            if( !window.jQuery){
                Modernizr.load('/scripts/jquery-1.11.1.min.js');
            }
        }
    },
    {
        load: '//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js',
        complete: function () {
            if ((typeof $().emulateTransitionEnd == 'function') == false) {
                Modernizr.load('/scripts/bootstrap.min.js');
            }
        }
    }
]);

这会尝试从CDN检索jQuery,如果无法执行此操作,则会加载本地版本。然后,它使用我的站点上的引导程序组件所需的Javascript重复该过程。

This attempts to retrieve jQuery from a CDN and if it is unable to do so, loads a local version. It then repeats the process with the Javascript required for my bootstrap components on my site.

我遇到的问题是我之后直接有一些jQuery代码:

The problem I have is that I then have some jQuery code directly following this:

$(document).ready(function () {
    $('.wishlist-toggle').click(function () {
        var nodeId = $(this).data("node");
        var id = $(this).data("id");
        var type = $(this).data("type");
        var addTo = $(this).data("add");
        var list = $(this).data("list");
        var removeFrom = $(this).data("remove");
        var storedCookie = getCookie("wishlist");
        var jsonString = null;
        var found = false;

...

出于某种原因,尽管在整个jQuery加载声明之后我在控制台中收到错误,指出$未定义。这通常是建议在调用自定义脚本的时候,不加载jQuery。

For some reason despite being after the whole jQuery loading declaration I am getting an error in my console specifying that $ is undefined. This would usually suggest that at the point at which by custom script is called, jQuery is not loaded.

我的问题是,通常如何做以及考虑什么在这种情况下最好的做法是确保在尝试运行自定义代码之前真正加载jQuery。

My question is, how would this usually be done and what is considered the best practise in this case to ensure that jQuery truly is loaded before attempting to run the custom code.

任何帮助,提示或指示都将不胜感激。

Any help, tips or pointers would be greatly appreciated.

推荐答案

尝试

var _jquery = function () {
    $(document).ready(function () {
        // do jquery stuff
        console.log("jQuery loaded");
        $("#jq").html("jquery version " + jQuery().jquery + " ready")
    })
};

var _bootstrap = function () {
    // do bootstrap stuff
    console.log("bootstrap loaded");
    $(".btn").trigger("click")
    .promise().done(function(el) {
      setTimeout(
      function() {
        $(el).trigger("click")
      }, 3000
      )
    });
};

var _load = function (url1, url2, test, callback) {
    var script = document.createElement("script");
    script.src = url1;
    script.type = "text/javascript";
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(script);
    setTimeout(function () {
        if (test()) {
            _load(url2, null, function() {return false}, callback)
        } else {
            callback()
        }
    }, 3000)
};

var _scripts = [
    ["//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
    , "//code.jquery.com/jquery-1.11.1.min.js", function () {
        return !window.jQuery
    },
    _jquery],
    ["//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js",
        "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js", function () {
        return (typeof $().emulateTransitionEnd == 'function') == false
    },
    _bootstrap]
];

_scripts.forEach(function (v) {
    _load(v[0], v[1], v[2], v[3]);
});

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <!-- Small modal -->
<button class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button>

<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
          <div id="jq"></div>
    </div>
  </div>
</div>
  </body>

这篇关于通过Modernizr加载jQuery后运行自定义代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆