Is it practically good to put JS files at the bottom of webpage?

前端 未结 7 1456
情歌与酒
情歌与酒 2020-12-18 03:26

It is widely recommended that JS files should be put at the bottom of page to allow html codes to be loaded first. In this case, visitors will see something when waiting for

7条回答
  •  悲&欢浪女
    2020-12-18 03:49

    Everybody's needs are different, lets go through your list:

    1) I've never had an issue with the layout or styling of the page because of javascript. If you have your HTML & CSS in order the missing javascript will be close to invisible. You can hide elements in the css and display them with javascript when they're ready. You can use jQuery's .show(); method

    here's an example:

    
    
    
      
      
    
    
      
      
    Hello 3,
    how
    are
    you?

    If you still have problems you can split up your javascript into ones your site relies on and other scripts and put some in the header and some in the footer.

    2) That's user error, you can't control that, but you could check if the needed functionality is there and attempt to reload it. Most plugins offer some sort of confirmation if they're running or not, so you could run a test and try to reload them.

    You can also delay loading of files until the user needs them, like waiting for them to focus on a form to load validation scripts or scroll past a certain point to load the code for things below "the fold"

    3) If the page dies you're going to get a half-blank page anyhow. With PHP 5 you can do better error handling with exceptions

     

    if (!$result = mysql_query('SELECT foo FROM bar', $db)) {
            throw new Exception('You fail: ' . mysql_error($db));
    }
    

    and this

    try
    {
      // Code that might throw an exception
      throw new Exception('Invalid URL.');
    }
    catch (FirstExceptionClass $exception) 
    {
      // Code that handles this exception
    } 
    catch (SecondExceptionClass $exception) 
    {
      // you get the idea what i mean ;)
    }
    

    4) If you minify your script you they shouldn't be much larger than images. JQuery is 32KB minified & gziped. JQuery-UI's script is 51KB. That's not too bad, most plugins should be even smaller than that.

    So I suggest you should do what you have to do to get the results you want, but search for best practices that reduce errors and excess code. There's always a better way to skin a cat...

提交回复
热议问题