Last active
February 15, 2021 18:08
-
-
Save kenchangh/cadb02e34d8409b4673e to your computer and use it in GitHub Desktop.
Injecting contents of external scripts into HTML string
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
// Implementation | |
function internalizeTextFiles(type, html, callback) { | |
var tagNames = { | |
js: 'script', | |
css: 'style' | |
} | |
var tagName = tagNames[type]; | |
var $html = $(html); | |
var $assets = $html.filter(tagName); | |
var fetchedCounter = 0; | |
$assets.each(function() { | |
var $asset = $(this); | |
var assetSource = $asset.attr('src'); | |
fetchAsset(assetSoource); | |
if (fetchedCounter === $assets.length) callback(html); | |
}); | |
function fetchAsset(url) { | |
$.ajax({ | |
url: url, | |
success: injectAsset | |
}).done(function() { | |
fetchedCounter++; | |
}); | |
function injectAsset(assetContent) { | |
var assetPattern = '<\s*' + tagName + '\s*src\s*=\s*"' | |
+ url + '"\s*\/?>'; | |
html.replace( | |
new RegExp(assetPattern, 'gim'), | |
'<script>' + assetContent + '</script>' | |
); | |
} | |
} | |
} | |
// Syntactic sugar | |
function internalizeJS(html, callback) { | |
internalizeAsset('js', html, callback); | |
} | |
function internalizeCSS(html, callback) { | |
internalizeAsset('css', html, callback); | |
} | |
// Usage example | |
var html = '<body><script src="/script.js"></body>'; | |
internalizeJS(html, function(newHtml) { | |
// <body><script>CONTENT OF SCRIPT</script></body> | |
console.log(newHtml); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment