简体   繁体   中英

javascript & jquery optimization question

I am creating a website that's being localized through JavaScript, however... I have alot of pages and in each page there are alot of text inputs items, I am using this plugin

http://code.google.com/p/jquery-watermark/

to apply watermark on my inputs, now I just need guides for better performance.

  1. Shall all watermarks be in one javascript file, or each page shall have it's own watermarks in it's own javascript file?

  2. Shall i create one JavaScript file having all the system $(object).watermark() (I am choosing objects by classes), or each page with it's own JavaScript file must contain the jQuery watermark line of code?

TBH I wouldn't do it this way. I would apply the watermarks (or placeholders as they're known) in the HTML, like so:

<input type="text" placeholder="Hello mum!" />

And I would then use jQuery and Moderizer to determine if the current browser supports placeholders or not. If it does, you don't need to worry as the hard work's been done. If it doesn't, you can use a script like this:

if ( !Modernizr.input.placeholder )
{
    $( '[placeholder]' ).focus( function()
    {
        var i   = $( this );

        if ( i.val() === i.attr( 'placeholder' ) )
        {
            i.val( '' );
        }
    }).blur( function()
    {
        var i   = $( this );

        if ( i.val() === '' )
        {
            i.val( i.attr( 'placeholder' ) );
        }
    }).blur();
}

This script essentially checks to see if the user has clicked into the input or not. If they have, it removes the placeholder as text. If they leave the input and they've left text in there, it doesn't change anything. However, if the input is empty, it then fills it with the placeholder.

I hope that helps.

General: normally you would have page specific things in a page specific javascript.

Your Problem; assuming your html looks something like this;

<input type='text' name='bla'></input>

You could rewrite it to read;

<input type='text' name='email' class='watermark' data-watertype='email'></input>

You could apply a single javascript snippet and inlcude it throughout the page;

    var texts={ "email":"Please enter a valid email address", .... },
        elems=jQuery("input.watermark"),
        elem,
        watermarkType;

    elems.each(function(i,elem){
        elem=jQuery(elem);
        watermarkType = texts[ elem.attr("data-watertype") ] || "";
        if (watermarkType.length!==0){
            //apply the watermark
            elem.watermark(watermarkType);
        }
    }
//this isn't tested but should work as expected!

thus resolving the need of having a specific javascript for each page to apply the watermarks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM