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

         在项目开发中,通常我们会引用未压缩的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,稍作修改。


你可能感兴趣的:(function,File,null,Path)