Search code examples
pluginsjoomlacontent-management-systemjoomla4

Joomla - Remove script tags from head with a custom plugin


I am making a content plugin that should do some changes on the website and load some scripts depending on the settings that the user made in the plugin. The problem, where I need help, is how to get all tags inside and do some changes and remove some tags. The tags that I want to remove are added from a third party plugin (it should be installed, can't just remove it).

onContentPrepare() has $article but the content is not there. I couldn't find the scirpts that I want to remove with getWebAssetManager(), probably not even registered there. onContentAfterDisplay() didn't help me and onBeforeCompileHead() same. I can add scripts and styles, but can't get a list from all tags that are there when the page is completely loaded.


Solution

  • The event you are looking for is onAfterRender(), which is a system plugin. You should add a system plugin, and invoke your code in the content plugin from there if you want to keep all the business logic in the content plugin.

    In onBeforeCompileHead() you get a list of scripts, yet to be written to the html output, which is easy to manipulate; but it is possible for an extension developer to include tags and scripts in the view markup or by echoing them, and you wouldn't have those in the document->_scripts array.

    In case the other plugin is also a system type, and in (unlikely) scenario it uses onAfterRender() to add its tags, you would only find the tags if your plugin is sorted after the offending plugin.

    You can check out my toomanyfiles plugin github repo (JED page) - compatibility up to Joomla 4.0 only, I haven't tested it on later versions. Its purpose is to heavily manipulate the header and specifically scripts and styles, compressing some, removing them, and adding the compressed version instead.

    Be warned that the code is unnecessarily complex, ugly and convoluted; but you'll find all the relevant calls and logic.