How to make Javascript in head load only after all elements has been loaded
<p>This is a image slider. Basically taken from w3school.</p>

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

<p>And the external js file:</p>

<pre><code>var slideIndex=1;
sliderFunction(slideIndex);

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

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

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