简体   繁体   中英

JS Import on HTML file

I'm testing toggles Class in JS script for frond-end purposes.

And I'm concern about the <script src="scripts.js"></script> import methods in HTML file.

When it was in <head> section of my script, it didn't worked. So, I imported in <body> and Voi lá! , it worked like magic.

This means that my JS script must be available in <body> for DOM purposes?

Best Regards for the community!

Yes, that's right. If the script you are importing needs to access DOM elements, it will need to be imported after the DOM elements are ready.

However, you can import the script in the HEAD if you want to but the script you are importing will need to have the following to listen for the DOMContentLoaded event:

Javascript:

document.addEventListener("DOMContentLoaded", function(event) {
    // your code to run - the DOM is ready!
});

jQuery:

$(document).ready(function() {
    // your code to run - the DOM is ready!
});

Or you can simply import the script at the bottom of the BODY like you have found out, and the DOM will be ready by the time the script is requested.

The DOM being ready does not necessarily mean any images are fully loaded. If you want to wait until all images, scripts and DOM are ready, you will need to listen for window's onLoad event to be fired, and that can be achieved by doing the following:

Javascript:

window.onload = function(e) {
    // do something when everything is ready
}

jQuery:

$(window).on('load', function(e) {
    // do something when everything is ready
});

It depends what the script does. If the script is looking for DOM elements immediately, it might not work in the head.

When the page loads, the browser reads from top to bottom . It the script is in the head, the script file is loaded and executed . But the html will not have been loaded yet. So if the script is looking for html, it will seem like the script doesn't work.

Something to read: https://developers.google.com/speed/docs/insights/BlockingJS

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