JQuery.Validate CDN fallback

故事扮演 提交于 2019-12-12 09:34:18

问题


A bit of a follow on from this question: Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

So I can detect if the JQuery CDN is down and allow for this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script type="text/javascript">
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='/Script/jquery-1.7.2.min.js' type='text/javascript'%3E%3C/script%3E"));
            }
</script>

How do I do the same for jquery.validate, when loaded as:

<script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>

回答1:


Use this instead:

if(typeof $().validate == 'undefined')
{
    /// same code as before except pointing at your local jQuery.validate path
}

DEMO - Check if validate exists

Returns true in the console if it exists and false if not.
Remove the script reference in the DEMO to get false as output.

Your complete code may look similar to this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>

<script type="text/javascript">
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/Script/jquery-1.7.2.min.js' type='text/javascript'%3E%3C/script%3E"));
    };

    if (typeof $().validate == 'undefined') {
        document.write(unescape("%3Cscript src='/Script/jquery.Validate-1.6.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>



回答2:


Something like this could do the trick

<script type="text/javascript" language="javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
    if (typeof jQuery().validate == 'undefined') {
        document.write(unescape("%3Cscript src='/js/jquery.validate.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script> 


来源:https://stackoverflow.com/questions/12564896/jquery-validate-cdn-fallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!