简体   繁体   English

在jQuery文档准备好之前加载Modernizr

[英]Loading Modernizr before jquery document ready

I'm using modernizr for the first time and facing some issues. 我是第一次使用modernizr,遇到了一些问题。

Here are the steps that I've done: 这是我已完成的步骤:

loaded Modernizr at the html header loaded JQuery at the html footer 在html标头处加载了Modernizr在html页脚处加载了JQuery

in the Jquery document ready I checked couple of browser capabilities using Modernizr. 在准备好的Jquery文档中,我使用Modernizr检查了几个浏览器功能。 If that check fails it will redirect to another page. 如果该检查失败,它将重定向到另一个页面。

Most of the time checking using Modernizr inside document ready works fine but sometimes it fails and redirect to another page even from the same browser. 在大多数情况下,使用在准备好文档中的Modernizr进行检查的工作正常,但有时会失败,甚至从同一浏览器重定向到另一个页面。

I guess it is because document ready loads before Modernizr thus Modernizr couldn't work. 我猜这是因为文档准备就绪在Modernizr之前加载,因此Modernizr无法正常工作。 Is there anything you could help me? 有什么可以帮助我的吗?

$(function() { 
    //if browser can't provide certain features, it will redirect the browser to dumb phone page

    if(satisfiedWithBrowser()){
        // do other stuff
    }else
        window.location = 'redirect/';
});

function satisfiedWithBrowser(){    
    //console.log(Modernizr);

    if(!Modernizr.csstransforms || !Modernizr.backgroundsize || !Modernizr.cssanimations || !Modernizr.hashchange) // || !Modernizr.touch)
        return false;
    else
        return true;
}

Thanks 谢谢

Yep sounds like you have a race condition, I would say there are two options to try: 是的,听起来像您有比赛条件,我想尝试一下两种方法:

  • Move moderniser to be alongside jQuery in the footer so that it is requested just before. 将modernizer移到页脚的jQuery旁边,以便在之前请求它。
  • Rather than waiting for $(document).ready() use $(window).load() . 而不是等待$(document).ready()使用$(window).load()

The first option should sort your problem. 第一种选择应该对您的问题进行排序。 The reason - at least as far as I have always understood the placing of script tags - is that when a script tag is in the body it gets requested as it is found / parsed, whereas script tags in the head will be triggered at different times depending on the browser (and on cache state) . 原因-至少就我一直以来了解的脚本标记的放置-原因是,当脚本标记在正文中时,它会在被查找/解析时被请求,而头部的脚本标记将在不同时间触发取决于浏览器(和缓存状态) You basically need to have both your script tags being loaded using the same method (either both at the footer, or both in head) . 基本上,您需要使用相同的方法(同时在页脚或在头部)加载两个脚本标签。

The second option should work as a fallback because rather than waiting for DOM readiness, you'll be waiting till window.load which should include waiting for all resources. 第二个选项应该作为后备,因为您将等待直到window.load,其中应包括等待所有资源,而不是等待DOM准备就绪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM