Programing

페이지로드 후 JavaScript를 실행하는 방법은 무엇입니까?

crosscheck 2020. 10. 2. 21:34
반응형

페이지로드 후 JavaScript를 실행하는 방법은 무엇입니까?


<script>내부를 사용하여 외부 스크립트를 실행하고 있습니다 <head>.

이제 페이지가로드 되기 전에 스크립트가 실행 되기 때문에 <body>무엇보다도에 액세스 할 수 없습니다 . 문서가 "로드 된"(HTML이 완전히 다운로드되고 RAM 내) 된 후 일부 JavaScript를 실행하고 싶습니다. 내 스크립트가 실행될 때 연결할 수있는 이벤트가 있습니까? 페이지로드시 트리거됩니다.


다음 솔루션이 작동합니다.

<body onload="script();">

또는

document.onload = function ...

또는

window.onload = function ...

참고 것을 마지막 옵션은 갈 수있는 더 좋은 방법 이 있기 때문에 unobstrusive 하고 더 표준으로 간주 .


스크립트가로드 시간에 실행되도록 함수를 설정하는 합리적으로 이식 가능하고 프레임 워크가 아닌 방법 :

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

페이지로드에는 두 개 이상의 단계가 있습니다. Btw, 이것은 순수한 JavaScript입니다

"DOMContentLoaded"

이 이벤트는 스타일 시트, 이미지 및 서브 프레임이로드를 완료 할 때까지 기다리지 않고 초기 HTML 문서가 완전히로드되고 파싱 되면 시작됩니다. 이 단계에서 사용자 장치 또는 대역폭 속도를 기반으로 이미지 및 CSS로드를 프로그래밍 방식으로 최적화 할 수 있습니다.

DOM이로드 된 후 실행됩니다 (img 및 css 전).

document.addEventListener("DOMContentLoaded", function(){
    //....
});

참고 : 동기식 JavaScript는 DOM 구문 분석을 일시 중지합니다. 사용자가 페이지를 요청한 후 가능한 빨리 DOM을 파싱하려면 JavaScript를 비동기식으로 전환 하고 스타일 시트로드를 최적화 할 수 있습니다.

"하중"

매우 다른 이벤트 인 load완전히로드 된 페이지 를 감지하는 데만 사용해야 합니다 . DOMContentLoaded가 훨씬 더 적절한 곳에서 load를 사용하는 것은 매우 일반적인 실수이므로주의해야합니다.

모든 것이로드되고 구문 분석 된 후 실행됩니다.

window.addEventListener("load", function(){
    // ....
});

MDN 리소스 :

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load

모든 이벤트의 MDN 목록 :

https://developer.mozilla.org/en-US/docs/Web/Events


본문 안에 "onload"속성을 넣을 수 있습니다.

...<body onload="myFunction()">...

또는 jQuery를 사용하는 경우 다음을 수행 할 수 있습니다.

$(document).ready(function(){ /*code here*/ }) 

or 

$(window).load(function(){ /*code here*/ })

귀하의 질문에 대한 답변이 되었기를 바랍니다.

$ (window) .load는 문서가 페이지에서 렌더링 된 후에 실행됩니다.


If the scripts are loaded within the <head> of the document, then it's possible use the defer attribute in script tag.

Example:

<script src="demo_defer.js" defer></script>

From https://developer.mozilla.org:

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.


Here's a script based on deferred js loading after the page is loaded,

<script type="text/javascript">
  function downloadJSAtOnload() {
      var element = document.createElement("script");
      element.src = "deferredfunctions.js";
      document.body.appendChild(element);
  }

  if (window.addEventListener)
      window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
      window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

Where do I place this?

Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).

What does it do?

This code says wait for the entire document to load, then load the external file deferredfunctions.js.

Here's an example of the above code - Defer Rendering of JS

I wrote this based on defered loading of javascript pagespeed google concept and also sourced from this article Defer loading javascript


Look at hooking document.onload or in jQuery $(document).load(...).


document.onreadystatechange = function(){
     if(document.readyState === 'complete'){
         /*code here*/
     }
}

look here: http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx


Working Fiddle

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
   alert("Page is loaded");
}
</script>
</head>

<body onload="myFunction()">
<h1>Hello World!</h1>
</body>    
</html>

<script type="text/javascript">
  function downloadJSAtOnload() {
   var element = document.createElement("script");
   element.src = "defer.js";
   document.body.appendChild(element);
  }
  if (window.addEventListener)
   window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
   window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

http://www.feedthebot.com/pagespeed/defer-loading-javascript.html


If you are using jQuery,

$(function() {...});

is equivalent to

$(document).ready(function () { })

See What event does JQuery $function() fire on?


<body onload="myFunction()">

This code works well.

But window.onload method has various dependencies. So it may not work all the time.


I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };

Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.


Using the YUI library (I love it):

YAHOO.util.Event.onDOMReady(function(){
    //your code
});

Portable and beautiful! However, if you don't use YUI for other stuff (see its doc) I would say that it's not worth to use it.

N.B. : to use this code you need to import 2 scripts

<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/event/event-min.js" ></script>

There is a very good documentation on How to detect if document has loaded using Javascript or Jquery.

Using the native Javascript this can be achieved

if (document.readyState === "complete") {
 init();
 }

This can also be done inside the interval

var interval = setInterval(function() {
    if(document.readyState === 'complete') {
        clearInterval(interval);
        init();
    }    
}, 100);

Eg By Mozilla

switch (document.readyState) {
  case "loading":
    // The document is still loading.
    break;
  case "interactive":
    // The document has finished loading. We can now access the DOM elements.
    var span = document.createElement("span");
    span.textContent = "A <span> element.";
    document.body.appendChild(span);
    break;
  case "complete":
    // The page is fully loaded.
    console.log("Page is loaded completely");
    break;
}

Using Jquery To check only if DOM is ready

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});

To check if all resources are loaded use window.load

 $( window ).load(function() {
        console.log( "window loaded" );
    });

Use this code with jQuery library, this would work perfectly fine.

$(window).bind("load", function() { 

  // your javascript event

});

$(window).on("load", function(){ ... });

.ready() works best for me.

$(document).ready(function(){ ... });

.load() will work, but it won't wait till the page is loaded.

jQuery(window).load(function () { ... });

Doesn't work for me, breaks the next-to inline script. I am also using jQuery 3.2.1 along with some other jQuery forks.

To hide my websites loading overlay, I use the following:

<script>
$(window).on("load", function(){
$('.loading-page').delay(3000).fadeOut(250);
});
</script>

As Daniel says, you could use document.onload.

The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.


My advise use asnyc attribute for script tag thats help you to load the external scripts after page load

<script type="text/javascript" src="a.js" async></script>
<script type="text/javascript" src="b.js" async></script>

use self execution onload function

window.onload = function (){
    /* statements */
}();   

<script type="text/javascript">
$(window).bind("load", function() { 

// your javascript event here

});
</script>

참고URL : https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load

반응형