根据不同环境加载不同js文件

5 篇文章 0 订阅

         在项目开发中,通常我们会引用未压缩的js文件,以便调试,但是在外网我们又需要将js进行压缩,这样每次上传都要更改js引用的代码,很不科学,所以采取js判断当前访问环境来进行加载js,这样就避免了之前的问题。例如,我们需要根据环境加载jquery-1.7.2.js或jquery-1.7.2.min.js

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title>Test loading different js</title>
    <script type="text/javascript" src="bootstrap.js"></script>
</head>
<body>
    
</body>
</html>

bootstrap.js代码:

(function(){
    var scripts = document.getElementsByTagName('script'),
    localhostTests = [
        /^localhost$/,
        /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?\b/ // IP v4
    ],
    host = window.location.hostname,
    isDevelopment = null,
    queryString = window.location.search,
    test, path, i, ln, scriptSrc, match;

    for (i = 0, len = scripts.length; i < len; i++) {
        scriptSrc = scripts[i].src;

        match = scriptSrc.match(/bootstrap\.js$/);

        if (match) {
            path = scriptSrc.substring(0, scriptSrc.length - match[0].length);
            break;
        }
    }

    if (queryString.match('(\\?|&)debug') !== null) {
        isDevelopment = true;
    }
    else if (queryString.match('(\\?|&)nodebug') !== null) {
        isDevelopment = false;
    }

    if (isDevelopment === null) {
        for (i = 0, ln = localhostTests.length; i < ln; i++) {
            test = localhostTests[i];

            if (host.search(test) !== -1) {
                isDevelopment = true;
                break;
            }
        }
    }

    if (isDevelopment === null && window.location.protocol === 'file:') {
        isDevelopment = true;
    }

    document.write('<script type="text/javascript" src="' + path + 'jquery-1.7.2' + ((isDevelopment) ? '' : '.min') + '.js"></script>');

转自ExtJs4,稍作修改。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值