簡體   English   中英

如何使用jquery生成和附加隨機字符串

[英]how to generate and append a random string using jquery

泛泛而談

我想使用jQuery或javascript將隨機字符串附加到元素的屬性。

細節

我需要引用一個存在於CDN上的CSS文件。 不幸的是,每次更新文件時,CDN都會更改此CSS文件的URL。 所以我不能簡單地引用一個靜態URL。

事實證明,如果你將一個字符串附加到CDN以前從未見過的URL的末尾,它將返回該文件的最新版本。 可以肯定的是。

例如

<link href="http://example.com/style.css?randomString-neverSeenBefore">

我知道,這是丑陋的,錯誤的和瘋狂的。 但有時這就是餅干崩潰的方式。 另一種方法是嘗試在奇偶校驗中保持越來越多的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) )
            );
    }

代碼#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 ); 

我假設需要“代碼#2” :我的假設是,我只是在現有的“href”屬性的末尾添加一個隨機數,什么都不會發生。 不會重新加載CSS文件。

萬分感謝您的幫助! :)

喬恩

添加隨機字符串稱為cache-buster。 你不應該在每個頁面加載時都這樣做,因為它完全違背了緩存的目的。

要回答如何使用隨機字符串完成它,您可以嘗試這樣做:

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

這是一個簡單的隨機字符串生成器函數:

/**
 * 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;
}

保持簡單,將當前時間戳(以毫秒為單位)應用於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 );

請注意,這真是一個壞主意,如果您不打算更改樣式表,只需在文件中手動替換URL。 有可用sed目的的工具(在基於Linux的系統下)

您只能獲得部分日期,例如:

var d = new Date;

// this string will change once a day for the same user
var rnd_str_day = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay();
href= 'http://example.com/style.css?' + rnd_str_day;

// this string will change once an hour
var rnd_str_hour = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay() + '_' + d.getHours();
href= 'http://example.com/style.css?' + rnd_str_hour;

所以css將每天或每小時緩存一次,具體取決於你的requeriments。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM