Skip to content

Instantly share code, notes, and snippets.

@kenchangh
Last active February 15, 2021 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kenchangh/cadb02e34d8409b4673e to your computer and use it in GitHub Desktop.
Save kenchangh/cadb02e34d8409b4673e to your computer and use it in GitHub Desktop.
Injecting contents of external scripts into HTML string
// 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