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?
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 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).
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.
$( 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.
I think you can use jQuery(document).ready() - Wait Until Exists
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With