Si el navegador ha cargado el documento y todos los recursos externos, puede cargar y disparar a través de un botón/clic basado en xmlhttprequest() ¿ Más archivos JavaScript y documentos HTML con archivos JavaScript integrados?
índice.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="rq.js"></script> </head> <body></body> </html>rq.js
function put() { const xhrURL = 'load.php'; const xhr = new XMLHttpRequest(); xhr.open('GET', xhrURL, false); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function bar() { if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { document.head.innerHTML += xhr.responseText; } }; xhr.send(null); } window.onload = function a() { // Button const btn = document.createElement('button'); btn.innerHTML = 'click here'; btn.value = 'click here'; btn.type = 'button'; btn.onclick = function p() { put(); }; document.body.appendChild(btn); };cargar.php
function loadSources() { readfile('page1.html'); echo '<script type="text/javascript" src="test.js"></script>'; } $_POST[loadSources()];pagina1.html
<script type="text/javascript" src="fromPage1.js"></script>fromPage1.js
console.log('from Page 1'); document.write('from Page 1');prueba.js
console.log('Testfile'); document.write('Testfile');Inesperado: Después de hacer clic en el botón Cargando los scripts pero el script no se ejecutó.
Esperado: Después de hacer clic en el botón Cargar, se ejecutan los scripts y el script.
Actualizar esta respuesta me ayudó: https://stackoverflow.com/a/47614491/9050912