简体   繁体   中英

How to make Javascript in head load only after all elements has been loaded

This is a image slider. Basically taken from w3school.

<head>
<script src="code.js"></script>
</head>
<body>
    <section id="slider">
        <img class="sliderImage" src="images/slider/1.jpg" style="width:100%">
        <img class="sliderImage" src="images/slider/2.jpg" style="width:100%">
        <img class="sliderImage" src="images/slider/3.jpg" style="width:100%">
        <img class="sliderImage" src="images/slider/4.jpg" style="width:100%">
        <a id="sliderprev" onclick="plusDivs(-1)"> &#10094; </a>
        <a id="slidernext" onclick="plusDivs(1)"> &#10095; </a>
    </section>
</body>

And the external js file:

var slideIndex=1;
sliderFunction(slideIndex);

function plusDivs(a){
    sliderFunction(slideIndex += a);
}

function sliderFunction(a){
    var i;
    var b = document.getElementsByClassName("sliderImage");
    if(a > b.length){
        slideIndex = 1;
    }
    if(a < 1){
        slideIndex = b.length;
    }
    for(i=0; i < b.length; i++){
        b[i].style.display = "none";
    }
    b[slideIndex-1].style.display = "block";
}

So it only works whenever I place <script> after those <image> and <a> . I know this that js file loads before document and that's causing the problem. How exactly do I solve this?

So it only works whenever I place after those <image> and <a> .

Which is what you should do , barring a good reason to do something else. Put your script tags at the very end of the document, just before the closing </body> tag. That way, all of the elements are available to the script code, and loading the scripts doesn't delay rendering the page.

If you have to put them elsewhere, use async or defer but beware of script loading order issues issues if you're using multiple scripts. (And check for proper support in your target browsers.)

If you can't do that, use the DOMContentLoaded event; all modern browsers support it:

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

You could use DOMContentLoaded .

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Example :

document.addEventListener('DOMContentLoaded', function() {
    var slideIndex=1;
    sliderFunction(slideIndex);
}, false);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM