Created
February 23, 2024 03:47
-
-
Save andirkh/5b367903d6b8a0fa4bc664a7b5a0de97 to your computer and use it in GitHub Desktop.
Redundant Script Remover
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
const Interaction = (id) => { | |
return ` | |
<div class="interactive-section" id="interactive-section-${id}"> | |
<button class="click-me-button" onclick="displayMessage(${id})">Click Me!</button> | |
<p class="output-message"></p> | |
</div> | |
<script> | |
function displayMessage(id) { | |
const outputMessage = document.querySelector('#interactive-section-' + id + ' .output-message'); | |
outputMessage.textContent = 'You clicked the button in section ' + id + '!'; | |
} | |
</script> | |
` | |
} | |
const htmlResult = ` | |
<html> | |
<body> | |
${Interaction(1)} | |
${Interaction(2)} | |
${Interaction(3)} | |
</body> | |
</html> | |
`.replace(/[\n\r\s\t]+/g, ' ') | |
.replace(/<!--[\s\S]*?-->/g, '') | |
.replace(/>\s+</g, '><').trim() | |
const removeRedundantScript = (htmlResult) => { | |
const scriptTags = htmlResult.match(/<script>[\s\S]*?<\/script>/g); | |
console.log('scriptTags', scriptTags) | |
if (!scriptTags) return htmlResult; | |
let result = htmlResult.replace(/<script>[\s\S]*?<\/script>/g, ''); | |
const uniqueScriptTags = []; | |
scriptTags.forEach(tag => { | |
if (!uniqueScriptTags.includes(tag)) { | |
uniqueScriptTags.push(tag); | |
} | |
}); | |
const lastIndex = result.lastIndexOf('</body>'); | |
result = result.slice(0, lastIndex) + uniqueScriptTags.join('') + result.slice(lastIndex) | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment