Manu Karki
Manu Karki

Reputation: 103

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?

Upvotes: 2

Views: 2995

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

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

Upvotes: 1

Related Questions