如何使用jquery生成和附加随机字符串

jon*_*jon 11 javascript jquery

泛泛而谈

我想使用jQuery或javascript将随机字符串附加到元素的属性.

细节

我需要引用一个存在于CDN上的CSS文件.不幸的是,每次更新文件时,CDN都会更改此CSS文件的URL.所以我不能简单地引用一个静态URL.

事实证明,如果你将一个字符串附加到CDN以前从未见过的URL的末尾,它将返回该文件的最新版本.可以肯定的是.

例如

<link href="http://example.com/style.css?randomString-neverSeenBefore">
Run Code Online (Sandbox Code Playgroud)

我知道,这是丑陋的,错误的和疯狂的.但有时这就是饼干崩溃的方式.另一种方法是尝试在奇偶校验中保持越来越多的CSS文件和模板标题...不可行.;)

到目前为止我得到了什么,

我的jQuery技能很少.我发现了两个不同的代码,它们可以完成我自己需要的工作,但是我不知道如何让我们知道如何让它们一起工作.

代码#1:

        // this guy is a random number generator that i found
        jQuery.extend({
        random: function(X) {
            return Math.floor(X * (Math.random() % 1));
        },
        randomBetween: function(MinV, MaxV) {
          return MinV + jQuery.random(MaxV - MinV + 1);
        }
    });


    // using above plugin, creates 20 random numbers between 10 and 99
    // and then appends that 40 digit number to a paragraph element
    for (i = 0; i < 20; i++) {
        $('p').text(    
            $('p').text() + ($.randomBetween(10, 99) )
            );
    }
Run Code Online (Sandbox Code Playgroud)

代码#2:

    // this fellow creates a link to the style sheet
    // after the page has loaded
    var link = $("<link>");
    link.attr({
            type: 'text/css',
            rel: 'stylesheet',
            href: 'http://example.com/style.css'
    });
    $("head").append( link ); 
Run Code Online (Sandbox Code Playgroud)

我假设需要"代码#2":我的假设是,我只是在现有的"href"属性的末尾添加一个随机数,什么都不会发生.即不会重新加载CSS文件.

万分感谢您的帮助!:)

乔恩

Ali*_*guy 28

添加随机字符串称为cache-buster.你不应该在每个页面加载时都这样做,因为它完全违背了缓存的目的.

要回答如何使用随机字符串完成它,您可以尝试这样做:

$('<link/>').attr({
                   type: 'text/css',
                   rel: 'stylesheet',
                   href: 'http://example.com/style.css?' + randString(4)
}).appendTo('head');
Run Code Online (Sandbox Code Playgroud)

这是一个简单的随机字符串生成器函数:

/**
 * Function generates a random string for use in unique IDs, etc
 *
 * @param <int> n - The length of the string
 */
function randString(n)
{
    if(!n)
    {
        n = 5;
    }

    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for(var i=0; i < n; i++)
    {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
}
Run Code Online (Sandbox Code Playgroud)

  • 关于缓存破坏的好消息.谢谢你的抬头! (3认同)

Lek*_*eyn 16

保持简单,将当前时间戳(以毫秒为单位)应用于URL:

// this fellow creates a link to the style sheet
// after the page has loaded
var link = $("<link>");
link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: 'http://example.com/style.css?' + (new Date).getTime()
});
$("head").append( link );
Run Code Online (Sandbox Code Playgroud)

请注意,这真是一个坏主意,如果您不打算更改样式表,只需在文件中手动替换URL.有可用sed于此目的的工具(在基于Linux的系统下)