Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready() in a bundled script

I've been doing a lot with web optimization recently, and I've come across an interesting problem. I was wondering if anyone might know of an existing solution.

Say you have multiple, page specific external .js files, each with it's own page specific $(document).ready() function. Say the document ready function for page 1 applies a style to every <li> in the body, while the document ready in page 2 only styles <input type="button" />s. Just a simple example.

Now say you bundle these 2 scripts, along with all your library scripts, to reduce the number of http requests on page load. Now, both document ready's will fire, and the li's on page 2 will be formatted with the code meant only for page 1.

My question is this - Is there a way through either jQuery or a third party library to assign a specific document ready to a specific page but still have them all bundled into one .js file?

like image 555
mccow002 Avatar asked Nov 01 '11 04:11

mccow002


People also ask

Does document ready wait for scripts?

The document. ready() function will be executed as soon as the DOM is loaded. It will not wait for the resources like images, scripts, objects, iframes, etc to get loaded.

Can we use multiple document ready () function on the same page?

Can we add more than one 'document. ready' function in a page? Yes we can do it as like I did in below example both the $(document).

Where do you put document ready?

So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.

What does $( document .ready function () mean?

$( document ).ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.


2 Answers

I think you can use jQuery(document).ready() - Wait Until Exists

like image 138
defau1t Avatar answered Sep 28 '22 16:09

defau1t


You should bundle your scripts according to your pages.

Lets say your homepage needs jquery, and some custom scripts. Bundle them together and reference this bundle.

For other pages like the profile page you bundle required scripts and reference it.

like image 38
Neelesh Avatar answered Sep 28 '22 17:09

Neelesh