Is it good practice to have "page specific" javascript? (for example, "onlyUsedOnOnePage.js")

I think this is a pretty beginner question,

I know that usually you will have a myCustomScript.js file on your site. But if you have a lot of Javascript that only applies to one page or the other, does it make sense to have.?



I just haven't seen this before, and I'm wondering why (maybe because the amount of "page-specific" javascript would be negligible in most cases?). But I have 2 big chunks that are only used on their respective pages and it seems to make sense in shortening the pageload to separate them. Bad idea?

//// EDIT /////

I think I just saw another answer that gives me the answer. "In small amounts, it really doesn't matter."

So how much .js code does one extra request cost? If I have "x" lines of code in "thisPageOnly.js" .. how many lines would have to justify an extra request?


source to share

1 answer

Yes, it makes sense. After all, any large web application will have JavaScript on the page.

To make it easier to work with java script files and pages, you can specify the space of your functions / classes that are related to siteX, prefixed with siteX. Don't forget to include in jQuery for jQuery for jtml output.

The reason why you might not have seen this is because when you name a space with your js, you can add it all in one js file and obfuscate or minimize that. If you have 10-20 page specific js files, you will make 10-20 requests which are not that good, so you have specific js content for the page, but including one time. And the way to do it is to specify the correct namespace for each page.

Have you already learned about prototypes and names?

Like this:

var yourPageNameSpace = {
    func1: function () {},
    func2: function() {}


then you make your file PageNameSpace.func1 ()

So shorter. Yes, this is fine for one or two pages, but not for every page. Consider namespaces in this situation.



All Articles