Question

I have a script that is running on page load, using PHP, and since output buffering is turned on, I have turned it off... however, since this is happening on page load, the code inside of the head tag for the page, using jQuery $(document).ready(function() { //... my code }); does not trigger until the entire page has been loaded.

I need to run this code before the page is loaded, but after jQuery has been loaded. I am using Google CDN for loading of jQuery. Any idea on how to do this without hitting an error saying $ is undefined?

Thanks.

Was it helpful?

Solution

<script> tags present in the HTML (without the defer or async tags) run in the order encountered in the HTML file. If you want some code to be executed immediately as soon as jQuery is available, then you can place that code in a <script> tag right after the <script> tag that loads jQuery.

<script src="jquery.js"></script>
<script>Your jQuery code here to run as soon as possible</script>

Keep in mind that just because jQuery is loaded, does not mean that the DOM from the document is loaded and is ready to operate on. If that's really what you need to wait for, then you will either need to place your scripts right before the </body> tag or use $(document).ready(fn) and wait until those events occur. Since jQuery is mostly about modifying the DOM, I'm curious what kind of jQuery code you want to run early before the DOM is ready?

If you are loading jQuery dynamically (which you didn't mention), you can also install a monitor for exactly when that dynamically loaded script finishes loading and respond to that event by running your code.

For a full description of the execution order of scripts, see this post: load and execute order of scripts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top