Topic: [Advice] Multiple extensions using prototype
Sharing some thought to other extension developers...
<hook id="hd_head"><![CDATA[
$forum_head['ex1_prototype'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
-------
<hook id="hd_head"><![CDATA[
$forum_head['ex2_prototype'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
I've come across a problem while developing an extension: what if both of them require prototype (javascript framework). Adding it twice is not only a waste, but would most likely provokes bunch of bugs, I could separate it as a third extension that others would require to run, but this is bothersome for users.
Looking at how js files are added to the header I finally found a satisfying work around.
<hook id="hd_head"><![CDATA[
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
-------
<hook id="hd_head"><![CDATA[
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
First we need to choose a single name for prototype across all extensions, I took "prototypejs".
This way, no matter how many extensions add it, only one file will be loaded because the last extension will override previous value for the "prototypejs" key.
<hook id="hd_head"><![CDATA[
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
-------
<hook id="hd_head"><![CDATA[
if(FORUM_PAGE === 'index') {
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
}
]]></hook>
One problem remains, let's imagine 2 extensions, one run only on index and the other applies on each page. The index one is parsed last. We would have 2 different files loaded depending on the page. This is a waste of time, bandwidth and cache.
<hook id="hd_head"><![CDATA[
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
]]></hook>
-------
<hook id="hd_head"><![CDATA[
if(FORUM_PAGE === 'index') {
if(!isset($forum_head['prototypejs'])) { $forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';}
}
]]></hook>
-------
<hook id="hd_head" priority="4"><![CDATA[
if(FORUM_PAGE === 'index') {
$forum_head['prototypejs'] = '<script type="text/javascript" src="'.$ext_info['url'].'/media/js/prototype.js"></script>';
}
]]></hook>
There's two way to solve this, either up the priority of the index's extension so it runs first, either add a condition to not override already existing prototypejs key.
That's all, hope it may be helpful to someone. It can applies to lot of things you wish to include only once across many extensions