在使用javascript加載js腳本之前,是否可以重寫html頁面中所有腳本標記的所有src?在頁面加載之前修改html頁面中所有腳本的src
我試圖使用<plaintext>
標籤,但我想知道是否有更好的解決方案。
在使用javascript加載js腳本之前,是否可以重寫html頁面中所有腳本標記的所有src?在頁面加載之前修改html頁面中所有腳本的src
我試圖使用<plaintext>
標籤,但我想知道是否有更好的解決方案。
我想我做了一個你想要的工作例子。它使用MutationObserver監聽節點對主體的更改,並在找到時更改所有腳本的src。它要求您的JavaScript在目標文件之前執行。
<script>
// select the target node
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type)
Array.from(document.querySelectorAll('script')).forEach(s => {
if (s.src && s.src.indexOf('jquery') !== -1) {
s.src = "" // this resets the script src
}
});
console.log('Jquery is loaded:', typeof $ !== 'undefined')
});
});
// configuration of the observer:
var config = {
childList: true
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js?hej"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js?oj"></script>
我不明白。根據文檔,https://developer.mozilla.org/en/docs/Web/API/MutationObserver事件在dom被更改後觸發,因此它開始從原始src下載腳本,我無法阻止它。 –
@GiuseppePes我認爲相同,但在我的例子中,它似乎阻止了腳本的執行。直到我測試它之前,我都不確定它會如何工作。 –
如果您查看網絡控制檯發出的請求,腳本會被提取,但看起來它不會執行它。 –
有什麼用呢?如果你首先執行你的JavaScript,你可以通過一個MutationObserver來監聽所有腳本節點,並在讀取它們時對它們進行編輯。 –
你想防止加載所有腳本? –
我想通過代理加載它們 –