how to generate and append a random string using jquery

前端 未结 3 1260
鱼传尺愫
鱼传尺愫 2021-02-08 04:36

Generalities

I\'d like to append a random string to an element\'s attribute, using either jQuery or javascript.

Specifics

I need to reference a CSS f

3条回答
  •  一整个雨季
    2021-02-08 04:56

    Adding a random string is called a cache-buster. You shouldn't do it on every page load as it completely defeats the purpose of cache.

    To answer how to accomplish it with a random string, you can try this:

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

    Here's a simple random string generator function:

    /**
     * Function generates a random string for use in unique IDs, etc
     *
     * @param  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;
    }
    

提交回复
热议问题