 
			
				12.01.2020, 22:03
			
			
			
		  
	 | 
 
	
		
		
		
			  | 
			
			
				
				
				 Профессор 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 27.05.2010 
					
					
					
						Сообщений: 33,150
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		Domik942,
  
<html>
<head>
    <meta http-equiv=content-type content="text/html;charset=UTF-8" />
    <title>test js page</title>
</head>
<body>
<div>the 1 tag</div>
<div>the 2 tag</div>
<div>the 3 tag</div>
<script>var testHtml = '<head><title>second page</title></head><body><p>test script</p>' +
    '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><\/script>' +
    '<script>alert("Hello 1");' +
    '$(function(){\n' +
    '    window.addEventListener("load", function (){\n' +
    '        alert ("onload 111");\n' +
    '    });\n' +
    '});'+
    'window.addEventListener("load", function (){\n' +
    '        alert ("onload 222");\n' +
    '    });'+
    '$(document).ready(function(){\n' +
    '    alert(jQuery.fn.jquery);\n' +
    '});</scr' + 'ipt>' +
    '<script>alert("Hello 2")<\/script>'+
    '<div>the 7 tag</div><div>the 8 tag</div><div>the 9 tag</div></body>';
var parser = new DOMParser();
var doc = parser.parseFromString(testHtml, 'text/html');
var htmlOld = document.querySelector('html');
var htmlNew = doc.querySelector('html');
document.replaceChild(htmlNew, htmlOld);
[...document.querySelectorAll('script')].reduce((promise, el) => {
    return promise.then(() => new Promise((resolve, reject) => {
        var s = document.createElement('script');
        if (el.text) {
            s.text = el.text;
            resolve();
        } else {
            s.onload = resolve;
            s.src = el.src;
        }
        el.parentNode.replaceChild(s, el);
    }))
}, Promise.resolve());
</script>
<div>the 4 tag</div>
<div>the 5 tag</div>
<div>the 6 tag</div>
</body>
</html>
 
		
	
		
		
		
		
		
		
	
		
			
			
	
			
			
			
			
			
				 
			
			
			
			
			
			
				
			
			
			
		 
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				12.01.2020, 22:22
			
			
			
		  
	 | 
 
	
		
		
		
			
			| 
			
				
				
				 Интересующийся 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 29.12.2019 
					
					
					
						Сообщений: 19
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	
		
			Сообщение от рони
			 
		
	 | 
 
	
		Domik942, 
 
<html>
 
	 | 
 
	
 
 Не могу понять почему, но "onload 111" у меня никогда не высвечивается.
 
jquery 1.12.4, в консоли никаких ошибок нет.  
		
	
		
		
		
		
		
		
	
		
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				12.01.2020, 22:48
			
			
			
		  
	 | 
 
	
		
		
		
			  | 
			
			
				
				
				 Профессор 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 27.05.2010 
					
					
					
						Сообщений: 33,150
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		Domik942, 
 скорее всего мало что грузится строка 28, событие load строка 17 назначается позднее.  
	
 
	| 
		
			 Цитата: 
		
	 | 
 
	| 
		Событие load происходит когда ресурс и его зависимые ресурсы закончили загружаться.
	 | 
 
	
 
 добавьте картинку и увидите оба сообщения.
 
<html>
<head>
    <meta http-equiv=content-type content="text/html;charset=UTF-8" />
    <title>test js page</title>
</head>
<body>
<div>the 1 tag</div>
<div>the 2 tag</div>
<div>the 3 tag</div>
<script>var testHtml = '<head><title>second page</title></head><body><p>test script</p>' +
    '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><\/script>' +
    '<script>alert("Hello 1");' +
    '$(function(){\n' +
    '    window.addEventListener("load", function (){\n' +
    '        alert ("onload 111");\n' +
    '    });\n' +
    '});'+
    'window.addEventListener("load", function (){\n' +
    '        alert ("onload 222");\n' +
    '    });'+
    '$(document).ready(function(){\n' +
    '    alert(jQuery.fn.jquery);\n' +
    '});</scr' + 'ipt>' +
    '<script>alert("Hello 2")<\/script>'+
    '<div>the 7 tag</div><div>the 8 tag</div><div>the 9 tag<img width="100%" src="https://unsplash.it/3000/3000/?random" /></div></body>';
var parser = new DOMParser();
var doc = parser.parseFromString(testHtml, 'text/html');
var htmlOld = document.querySelector('html');
var htmlNew = doc.querySelector('html');
document.replaceChild(htmlNew, htmlOld);
[...document.querySelectorAll('script')].reduce((promise, el) => {
    return promise.then(() => new Promise((resolve, reject) => {
        var s = document.createElement('script');
        if (el.text) {
            s.text = el.text;
            resolve();
        } else {
            s.onload = resolve;
            s.src = el.src;
        }
        el.parentNode.replaceChild(s, el);
    }))
}, Promise.resolve());
</script>
<div>the 4 tag</div>
<div>the 5 tag</div>
<div>the 6 tag</div>
</body>
</html>
 
		
	
		
		
		
		
		
		
	
		
			
			
	
			
			
			
			
			
				 
			
			
			
			
			
			
				
			
			
			
		 
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
	
		
	
		
		
		
			
			 
			
				12.01.2020, 23:12
			
			
			
		  
	 | 
 
	
		
		
		
			
			| 
			
				
				
				 Интересующийся 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 29.12.2019 
					
					
					
						Сообщений: 19
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	
		
			Сообщение от рони
			 
		
	 | 
 
	
		 скорее всего мало что грузится строка 28, событие load строка 17 назначается позднее.  
добавьте картинку и увидите оба сообщения.
	 | 
 
	
 
 
Интересно то что если страница статическая, то всё работает нормально. Единственное что "onload 111" выполняется последним.
 
<head><title>second page</title></head><body><p>test script</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
'<script>alert("Hello 1");
$(function(){
    window.addEventListener("load", function (){
        alert ("onload 111");
    });
});
window.addEventListener("load", function (){
    alert ("onload 222");
});
$(document).ready(function(){
    alert(jQuery.fn.jquery);
});</script>' +
<script>alert("Hello 2")</script>
<div>the 7 tag</div><div>the 8 tag</div><div>the 9 tag</div></body>
 
		
	
		
		
		
		
		
		
	
		
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				12.01.2020, 23:17
			
			
			
		  
	 | 
 
	
		
		
		
			  | 
			
			
				
				
				 Профессор 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 27.05.2010 
					
					
					
						Сообщений: 33,150
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	| 
		
			Сообщение от Domik942
			
		
	 | 
 
	| 
		Единственное что "onload 111"
	 | 
 
	
 
 так вы же сами назначили его  после загрузки html строка 4. $(function(){
а строка 9 (напрямую/ сразу) 
строка 9 сработает раньше чем строка 5  
		
	
		
		
		
		
		
		
	
		
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				13.01.2020, 21:12
			
			
			
		  
	 | 
 
	
		
		
		
			
			| 
			
				
				
				 Интересующийся 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 29.12.2019 
					
					
					
						Сообщений: 19
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	
		
			Сообщение от рони
			 
		
	 | 
 
	
		так вы же сами назначили его после загрузки html строка 4.$(function(){ 
 
а строка 9 (напрямую/сразу) 
строка 9 сработает раньше чем строка 5
	 | 
 
	
 
 Подскажите пожалуйста как мне переделать этот кусок кода под динамическое добавление на страницу, чтобы он работал корректно, так же как в статическом его варианте ? 
 
<html><head><title>second page</title></head><body><p>test script</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    alert("Hello 1");
    $(function(){
        var text2 = "test message here\n\n11\n2\n3";
        TEST = text2, window.onbeforeunload = function(a) {
            var c = TEST;
            return a.returnValue = c;
        }, window.onload = function() {
            if (confirm(TEST)) {
                alert("its okay");
            } else {
                alert("cancelled");
            }
        };
    });
    window.addEventListener("load", function (){
        alert ("onload 222");
    });
    $(document).ready(function(){
        alert(jQuery.fn.jquery);
    });
</script>
<script>alert("Hello 2")</script>
<div>the 7 tag</div><div>the 8 tag</div><div>the 9 tag</div></body></html>
 
		
	
		
		
		
		
		
		
	
		
			
			
	
			
			
			
			
			
				 
			
			
			
			
			
			
				
			
			
			
		 
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				13.01.2020, 21:49
			
			
			
		  
	 | 
 
	
		
		
		
			  | 
			
			
				
				
				 Профессор 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 27.05.2010 
					
					
					
						Сообщений: 33,150
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		Domik942,
  
<html>
<head>
    <meta http-equiv=content-type content="text/html;charset=UTF-8" />
    <title>test js page</title>
</head>
<body>
<div>the 1 tag</div>
<div>the 2 tag</div>
<div>the 3 tag</div>
<script>
var testHtml = '<html><head><title>second page</title></head><body><p>test script</p>'+
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><\/script>'+
'<script>'+
'    alert("Hello 1");'+
'    $(function(){'+
'        var text2 = "test message here\\n\\n11\\n2\\n3";'+
'        TEST = text2, window.onbeforeunload = function(a) {'+
'            var c = TEST;'+
'            return a.returnValue = c;'+
'        }, window.onload = function() {'+
'            if (confirm(TEST)) {'+
'                alert("its okay");'+
'            } else {'+
'                alert("cancelled");'+
'            }'+
'        };'+
'    });'+
'    window.addEventListener("load", function (){ '+
'        alert ("onload 222");'+
'    });'+
'    $(document).ready(function(){ '+
'        alert(jQuery.fn.jquery);  '+
'    });'+
'<\/script> '+
'<script>alert("Hello 2")<\/sc'+'ript>'+
'<div>the 7 tag</div><div>the 8 tag</div><div>the 9 tag</div></body></html>';
var parser = new DOMParser();
var doc = parser.parseFromString(testHtml, 'text/html');
var htmlOld = document.querySelector('html');
var htmlNew = doc.querySelector('html');
document.replaceChild(htmlNew, htmlOld);
[...document.querySelectorAll('script')].reduce((promise, el) => {
    return promise.then(() => new Promise((resolve, reject) => {
        var s = document.createElement('script');
        if (el.text) {
            s.text = el.text;
            resolve();
        } else {
            s.onload = resolve;
            s.src = el.src;
        }
        el.parentNode.replaceChild(s, el);
    }))
}, Promise.resolve());
</script>
<div>the 4 tag</div>
<div>the 5 tag</div>
<div>the 6 tag</div>
</body>
</html>
 
		
	
		
		
		
		
		
		
	
		
			
			
	
			
			
			
			
			
				 
			
			
			
			
			
			
				
			
			
			
		 
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				13.01.2020, 22:21
			
			
			
		  
	 | 
 
	
		
		
		
			
			| 
			
				
				
				 Интересующийся 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 29.12.2019 
					
					
					
						Сообщений: 19
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	
		
			Сообщение от рони
			 
		
	 | 
 
	
		 
<html>
<head>
    <meta http-equiv=content-type content="text/html;charset=UTF-8" />
    <title>test js page</title>
</head>
	 | 
 
	
 
 Я не могу понять в чём ошибка, но у меня не отображается "its okay" либо "cancelled". Подумал что может быть проблема в браузере, пробовал изначально в Firefox, на хроме тоже самое. Все алерты отображаются кроме тех confirm(TEST).  
		
	
		
		
		
		
		
		
	
		
		
	
	
	 | 
 
 
	 
		 | 
 
 
	
	
	
		
	
		
		
		
			
			 
			
				13.01.2020, 22:45
			
			
			
		  
	 | 
 
	
		
		
		
			  | 
			
			
				
				
				 Профессор 
				
				
				
				
	
 
 
 
			 | 
			  | 
			
				
				
					Регистрация: 27.05.2010 
					
					
					
						Сообщений: 33,150
					 
					
					
			
		
 
		 
		
			 | 
		 
		 
		
	 | 
 
	
	
	
		
		
		
		
		
	
 
	| 
		
			Сообщение от Domik942
			
		
	 | 
 
	| 
		Я не могу понять в чём ошибка,
	 | 
 
	
 
 
	
 
	| 
		
			Сообщение от рони
			
		
	 | 
 
	| 
		так вы же сами назначили его после загрузки html строка 4.$(function(){
	 | 
 
	
 
 обработка события ставится позднее чем само событие, всё загружено уже, события onload не будет. 
вам дали ссылку на решение 
 https://learn.javascript.ru/onload-o...ded#readystate
$(function() {
function work() {
    if (confirm(TEST)) {
                alert("its okay");
            } else {
                alert("cancelled");
            } }
if (document.readyState == 'loading') {
  // ещё загружается, ждём события
  window.onload = work; // лучше window.addEventListener("load", work)
} else {
  // DOM готов!
  work();
}
});
 
		
	
		
		
		
		
		
		
	
		
		
	
	
	 | 
 
 
	 
		 | 
 
 
 
 |  
  |