Javascript Wait Until jQuery Loads

Ok, if you are like me, you’ve probably had the need to put a small snippet of Javascript between some <script> tags in a view. But, if the rest of your javascript is loaded somewhere in the footer of your layout, then at the point you run that embedded snippet, none of your other libraries will have been loaded.

Allow me to introduce you to a little technique that can be an interesting workaround. I can’t claim to have found this trick as I ran across it on an awesome StackOverflow answer.

Allow me to explain what is going on here.  You will notice the function is wrapped with parenthesis followed by another set of parenthesis. This is called an immediately invoked function expression (IIFE), which is a fancy way of saying that it will run automatically when the code is loaded. When it runs, it checks to see if the window.jQuery object exists and if not, it sets a timeout for 50ms and tries again. This will continuously loop until it detects that the jQuery object exists in the global namespace and will then run your code.

This doesn’t only apply to jQuery. For my use case, I had a javascript object that I needed to set a counter based on values loaded in from a form with dynamic sections. This is  how I made that work:

You will notice the {{ … }} syntax in there. That is the blade templating language in Laravel. For my use case, I needed to generate 0 to N instances of a template and keep track in javascript how many I had so that the next instance generated client side had the appropriate numbers applied to input field names. Probably not the best way to do things, but definitely functional.

 

Laravel 4 Session Not Persisting

I pulled out my hair trying to get sessions to persist in Laravel 4 for quite a while. I combed over my code a hundred times and Googled until my eyes bled trying to figure it out. This was my test:

As it turns out, it had to do with my Session configuration in config/session.php. I set my cookie name to something like this:

The lesson here is DO NOT PUT PUNCTUATION IN YOUR COOKIE NAME! Once I removed the period from that cookie name, everything worked fine.

Hope that helps!