Skip to content
This repository has been archived by the owner on Mar 31, 2023. It is now read-only.

Commit

Permalink
script with callback loading
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan Willhite committed Nov 27, 2018
1 parent 07d8614 commit 3454729
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions components/js/reload-scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,34 @@
* Reload Scripts on page (required for attach_library)
*
*/

const d = document;
// Get body tag.
const head = document.getElementsByTagName('body')[0];
const head = d.getElementsByTagName('body')[0];
// Get scripts within the body.
const scripts = head.querySelectorAll('script');

scripts.forEach((element) => {
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) {
// Create new script element.
const script = document.createElement('script');
// Set src to script above.
script.src = element.dataset.src;
// Append to head.
head.appendChild(script);
async(element.dataset.src, () => {
if (typeof Drupal === 'object' && typeof Drupal.attachBehaviors === 'function') {
Drupal.attachBehaviors();
}
});
}
});

0 comments on commit 3454729

Please sign in to comment.