4

Alright, I am trying to do a very simple thing: use jQuery in my myScript.js file. I'm on Magento 1.9.0.1. The theme I am building is based on the built-in rwd theme, which by default loads jQuery 1.10.2 in noConflict mode, locally (as opposed to Google cdn). If I attempt to make a jQuery funtion in myScript.js, I get the following error (in my Chrome dev console): ReferenceError: jQuery is not defined. However, if I put the same function inside of <script> somewhere in the HTML, it works as expected.

So, I have done some researching and poking around and it seems the problem is coming from the load order of .js files in the page head, where myScript.js is being loaded before jquery-1.10.2.min.js. I have tried a lot of different things to fix this (attempting to call myScript.js after jQuery)—I have moved the line in page.xml that calls jQuery to before the myScript.js call. I have moved the myScript call to local.xml, where I put it at the very bottom. No matter what I do, I cannot get myScript.js to load after jquery-1.10.2.min.js. The load order in the <head> will always, always be the exact same, regardless of the order I list them in. I can get either file to not load at all by removing it's call from page.xml, so I know that I am editing the correct file.

TL;DR: How can I get myScript.js to load after jQuery?

Thanks in advance!

P.S. Am I using the backtick markdown properly in my question? It feels like I am using it really often, but I believe I am following to guidelines. Any stylistic help would be appreciated :)

3

Answer

To force it to load after jQuery in the head don't use addJs, rather use <action method="addItem"><type>skin_js</type> as skin is loaded after libraries (addJs)

As a side note

  1. My preferred method of scripting custom jQuery is to add templates to before_body_end; there is no addJs action for this so instead you'll be creating a template file which includes the script tag with getSkinUrl. This ensures that your script is non-blocking. In Magento this may be considered to be laughable (due to the vast number of scripts in head) but rather adhere to best practice where your customizations are concerned.

  2. Rather than use jQuery the RWD framework uses noConflict to alias it to $j:

File: skin/frontend/rwd/default/js/app.js

// ==============================================
// jQuery Init
// ==============================================

// Avoid PrototypeJS conflicts, assign jQuery to $j instead of $
var $j = jQuery.noConflict();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.