This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #288 from fourkitchens/attach_library-fixes
move drupal js loading to head, reload scripts
- Loading branch information
Showing
3 changed files
with
57 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/* | ||
* Reload Scripts on page (required for attach_library) | ||
* | ||
*/ | ||
const d = document; | ||
// Get body tag. | ||
const head = d.getElementsByTagName('body')[0]; | ||
// Get scripts within the body. | ||
const scripts = head.querySelectorAll('script'); | ||
const scriptsArray = []; | ||
|
||
function async(src, callback) { | ||
const script = document.createElement('script'); | ||
script.src = src; | ||
if (callback) { | ||
script.addEventListener( | ||
"load", | ||
e => { | ||
callback(null, e); | ||
}, | ||
false | ||
); | ||
} | ||
head.appendChild(script); | ||
} | ||
|
||
scripts.forEach(element => { | ||
// If the script has the data-name attribute. | ||
if (element.dataset.name) { | ||
const scriptSrc = element.dataset.src; | ||
if (!scriptsArray.includes(scriptSrc)) { | ||
async(scriptSrc, () => { | ||
if (typeof Drupal === 'object' && typeof Drupal.attachBehaviors === 'function') { | ||
const behaviors = Object.values(Drupal.behaviors); | ||
// Only run attachBehaviors once. | ||
behaviors.forEach(behavior => { | ||
Drupal.attachBehaviors(); | ||
}); | ||
} | ||
}); | ||
scriptsArray.push(scriptSrc); | ||
} | ||
} | ||
}); |