Petty_Crim
Petty_Crim

Reputation: 441

Javascript Performance - Adding Scripts with $.getScript()

I am currently making a sort of web app and part of it works by dynamically loading and adding js scripts to the page. For this I am using JQuery's $.getScript() method which loads it in.

I have it set as cached.

With my program if a script already exists it is loaded again anyway, from what appears to be cache. What I am wondering though is how much would this effect the site and performance. Does a newly loaded script that has the same src as an existing one overwrite the previous one or is the new one added alongside the old one?

Further more as my site is an AJAX site its possible for several scripts from different pages to eventually be loaded up over time. Is there any browser restrictions on how many scripts one can have loaded?

Upvotes: 1

Views: 892

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49218

I think Ilya has provided some great points to consider, and I think that answers your specific question. If what you're trying to accomplish, however, is rerunning a $(document).ready() handler, you could do:

(function(){
    var myreadyfunction = function(){
        $('#affected').toggleClass('blue');
    };

    $(document).ready(myreadyfunction);

    $(document).ready(function(){
        $('button').click(myreadyfunction);
    });
})();

http://jsfiddle.net/Z97cm/

I've scoped it into an anonymous (function(){})(); to keep out of the global scope, so you might want to consider that if you need to access that function from outside that scope. But that gives you the general idea of what I was talking about.

Upvotes: 1

Ilya Volodin
Ilya Volodin

Reputation: 11256

It will affect site performance. Even if your script is cached on the client with expiration set the browser still needs to parse and execute newly included script. More than that, there's a very good chance you will run into javascript errors because you scripts will override variables already set by previous version. JavaScript parsing and executing is still a blocking operation in all browsers, so while your file is being processed your UI will lock up.

To answer second part of the question, as far as I know there's no limit of number of javascript files on a given page. I've seen pages with over 200 javascripts that didn't throw any exceptions.

Upvotes: 2

Related Questions