سؤال

أقوم بتنفيذ برنامج نصي خارجي باستخدام ملف <script> داخل <head>.

الآن منذ تنفيذ البرنامج النصي قبل لقد تم تحميل الصفحة، لا أستطيع الوصول إليها <body>, ، ضمن أشياء أخرى.أرغب في تنفيذ بعض برامج JavaScript بعد "تحميل" المستند (تنزيل HTML بالكامل وذاكرة الوصول العشوائي).هل هناك أي أحداث يمكنني ربطها عند تنفيذ البرنامج النصي الخاص بي، والتي سيتم تشغيلها عند تحميل الصفحة؟

هل كانت مفيدة؟

المحلول

هذه الحلول ستعمل:

<body onload="script();">

أو

document.onload = function ...

او حتى

window.onload = function ...

لاحظ أن الخيار الأخير هو طريقة أفضل للذهاب لأنه غيرالي وهو تعتبر أكثر معيارًا.

نصائح أخرى

وسيلة محمولة بشكل معقول ، غير فرعي لوجود البرنامج النصي الخاص بك تعيين وظيفة لتشغيلها في وقت التحميل:

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;
    }
}

ضع في اعتبارك أن تحميل الصفحة يحتوي على أكثر من مرحلة واحدة. راجع للشغل ، هذا هو جافا سكريبت نقي

"DomContentloaded"

يتم إطلاق هذا الحدث عند تم تحميل وثيقة HTML الأولية بالكامل وتحليلها, ، دون انتظار أوراق الأنماط والصور والأطر الفرعية لإنهاء التحميل. في هذه المرحلة ، يمكنك تحسين تحميل الصور و CSS استنادًا إلى جهاز المستخدم أو سرعة النطاق الترددي.

يتم تحميل Exectues بعد DOM (قبل IMG و CSS):

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

ملاحظة: يتوقف JavaScript المتزامن عن تحليل DOM. إذا كنت تريد أن يتم تحليل DOM بأسرع وقت ممكن بعد أن طلب المستخدم الصفحة ، يمكنك اقلب JavaScript غير متزامن و تحسين تحميل أوراق الأنماط

"حمل"

حدث مختلف تمامًا ، حمل, ، يجب استخدامها فقط للكشف صفحة محملة بالكامل. إنه خطأ شائع بشكل لا يصدق لاستخدام الحمل حيث سيكون DomContentloading أكثر ملاءمة ، لذا كن حذرًا.

خسوفات بعد تحميل كل شيء وتحليلها:

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 بعد تقديم المستند على صفحتك.

إذا تم تحميل البرامج النصية داخل <head> من المستند ، ثم من الممكن استخدام defer سمة في علامة البرنامج النصي.

مثال:

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

من https://developer.mozilla.org:

تأجيل

تم تعيين هذه السمة المنطقية للإشارة إلى متصفح أن البرنامج النصي من المفترض أن يتم تنفيذها بعد تحليل المستند ، ولكن قبل إطلاق DomContented.

يجب عدم استخدام هذه السمة إذا كانت سمة SRC غائبة (أي للنصوص المضمنة) ، في هذه الحالة لن يكون لها أي تأثير.

لتحقيق تأثير مماثل للبرامج النصية التي تم إدراجها ديناميكيًا ، استخدم ASYNC = FALSE بدلاً من ذلك. سيتم تنفيذ البرامج النصية مع السمة المؤجلة بالترتيب الذي تظهر به في المستند.

فيما يلي نص برمجي يعتمد على تحميل js المؤجل بعد تحميل الصفحة،

<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>

أين أضع هذا؟

الصق الكود في HTML الخاص بك قبل </body> العلامة (بالقرب من أسفل ملف HTML الخاص بك).

ماذا تعمل، أو ماذا تفعل؟

يقول هذا الرمز الانتظار حتى يتم تحميل المستند بأكمله ، ثم قم بتحميل الملف الخارجي deferredfunctions.js.

فيما يلي مثال على الكود أعلاه - تأجيل تقديم JS

لقد كتبت هذا على أساس تحميل مؤجل لجافا سكريبت مفهوم pagespeed جوجل ومصدره أيضًا من هذه المقالة تأجيل تحميل جافا سكريبت

انظر إلى التثبيت document.onload أو في jQuery $(document).load(...).

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

انظر هنا: http://msdn.microsoft.com/en-us/library/ie/MS536957(V=VS.85).aspx

Best method, recommended by Google also. :)

<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

Working Fiddle

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

<body onload="myFunction()">
<h1>Hello World!</h1>
</body>    
</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() { }.

$(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>

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

});

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>

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

// your javascript event here

});
</script>

use self execution onload function

window.onload = function (){
    /* statements */
}();   
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top