Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize JavaScript CSS download

I have a number of pages for my website all use jQuery and JSON and the same CSS, except for a few pages. The first page is user login. As the user will take time to type in his username and password, I want to download all the required JavaScript and CSS files for the entire user session during login. How can this be done? The header is the same for all pages. How do I optimize it?

like image 355
rohitnaidu19 Avatar asked Jul 31 '12 08:07

rohitnaidu19


People also ask

How do I optimize CSS files?

To optimize the CSSOM construction, remove unnecessary styles, minify, compress and cache it, and split CSS not required at page load into additional files to reduce CSS render blocking.

Does CSS affect performance?

Stylesheets account for 60 kB split over seven requests, so it's rarely a top priority when attempting to address performance issues. However, CSS does have an effect, however slight it may seem. Once you've addressed your JavaScript, learning to optimize CSS properly should be the next priority.


2 Answers

My idea would be load in js and css files dynamically after document.load. This would not affect the load time of the login page, whilst also caching your js and css files once the user has logged in.

You could also easily change this to document.ready if it loads faster for you.

What about something like this?

$(document).load(function() {
    function preloadFile(filename, filetype){

        //For javascript files
        if (filetype=="js"){
            var fileref=document.createElement('script');
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src", filename);
        }

        //For CSS files
        else if (filetype=="css") {
            var fileref=document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }

        document.getElementsByTagName("head")[0].appendChild(fileref)
    }

    //Examples of how to use below
    preloadFile("myscript.js", "js"); 
    preloadFile("javascript.php", "js");
    preloadFile("mystyle.css", "css");
});

References

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

like image 157
Undefined Avatar answered Nov 15 '22 14:11

Undefined


  • Add all your css/javascript on your login page.
  • Put all your css at the top in HEAD section.
  • Put all your Javascripts at the bottom.
  • Also make your Javascripts and CSS as external files as they are cached by browser(rather than writing the inline javascript and css in the page).

  • Minify your Javascript and CSS

UPDATE 2

Post loading of JS and CSS could also be done using YUI GET UTILITY

For more details look at this Yahoo : Best Practises for Optimizing your WebSite

like image 27
Anand Avatar answered Nov 15 '22 15:11

Anand