magento2
magento2 copied to clipboard
Incorrect JavaScript File Loading Order After Enabling CSP module
I am encountering an issue with the loading order of JavaScript files (require.js
, mixins.js
, requirejs-config.js
) after enabling Content Security Policy (CSP) in Magento 2. This appears to be breaking JavaScript bundling, causing improper execution order and related issues.
Reproduction Steps:
- Enable CSP in Magento 2.
- Notice the incorrect loading order of JavaScript files:
require.js
,mixins.js
,requirejs-config.js
. - This issue also affects JavaScript bundling functionality, leading to performance degradation.
Screenshots:
-
Before enabling CSP: Correct file order (Screenshot below)
-
After enabling CSP: Incorrect file loading order
Cause:
It seems that the issue is related to CSP configurations interfering with the loading order and possibly the integrity attribute (hash) of JavaScript assets, specifically in how property groups are handled within GroupedCollection
.
In this file, the integrity attributes (hash) should be ignored when grouping properties.
Proposed Workaround: (doesn't work properly broke integrity :( )
I suggest modifying the grouping logic to disregard the integrity
attribute when comparing asset properties.
Example workaround code:
private function clearGroupProperties(array $properties)
{
if (isset($properties['attributes']['integrity'])) {
unset($properties['attributes']['integrity']);
}
return $properties;
}
/**
* Retrieve existing or new group matching the properties
*
* @param array $properties
* @return PropertyGroup
*/
private function getGroupFor(array $properties)
{
/** @var $existingGroup PropertyGroup */
foreach ($this->groups as $existingGroup) {
$existingGroupProperties = $existingGroup->getProperties();
if ($this->clearGroupProperties($existingGroupProperties) == $this->clearGroupProperties($properties)) {
return $existingGroup;
}
}
/** @var $newGroup PropertyGroup */
$newGroup = $this->propertyFactory->create(['properties' => $properties]);
$this->groups[] = $newGroup;
return $newGroup;
}
Expected Outcome:
- After this modification, JavaScript files should load in the correct order.
- JavaScript bundling should function correctly even with CSP enabled.