I need to include a JavaScript file after certain other JavaScript files. Normally, I would just include it in the XML file using syntax like:
<action method="addJs"><script>myfile.js</script></action>
or
<action method="addItem"><type>js</type><name>myfile.js</name></action>
in the correct order, so files are included the way I want.
The point is, though, I won't know how many times I have to include my file. To be more specyfic, I'm trying to include a file with jQuery.noConflict() after every instance of jquery*.js file. The website I'm working on is still under development and there might still be added some new extensions that include their own jquery library (and I might not even be aware of that as I am not the only person working on the project).
Is there any event on including js file when rendering the layout on the frontend or maybe there is some method I could rewrite to achieve the desired effect?
The only way to add an inclusion of script X after every inclusion of script Y, is to modify the function that does the adding.
Open app/code/core/Mage/Page/Block/Html/Head.php, and modify the function getCssJsHtml. Like this:
public function getCssJsHtml()
{
// separate items by types
$lines = array();
foreach ($this->_data['items'] as $item) {
if (!is_null($item['cond']) && !$this->getData($item['cond']) || !isset($item['name'])) {
continue;
}
$if = !empty($item['if']) ? $item['if'] : '';
$params = !empty($item['params']) ? $item['params'] : '';
switch ($item['type']) {
case 'js': // js/*.js
case 'skin_js': // skin/*/*.js
case 'js_css': // js/*.css
case 'skin_css': // skin/*/*.css
$lines[$if][$item['type']][$params][$item['name']] = $item['name'];
if(stripos($item['name'], 'jquery') !== false)$lines[$if][$item['type']][$params]['2_'.$item['name']] = $yourfilename;
break;
default:
$this->_separateOtherHtmlHeadElements($lines, $if, $item['type'], $params, $item['name'], $item);
break;
}
}
...
You see I've added a check to see whether the file being added is jquery (stripos($item['name'], 'jquery') !== false
), and if so, add a new item right after it with the path $yourfilename
.
Magento was supposed to already have the ability to sort skin files, but that a) relies on everyone supplying a sort attribute, and b) never actually worked properly in the first place.