Steven Aguilar
Steven Aguilar

Reputation: 3049

Turbolinks: JavaScript fires before DOM is fully loaded

I'm currently working on a Rails 6 application using JavaScript. I have a file javascript/packs/posts.js which seems to be firing before the DOM has finished loading. I have tried the following without luck.

document.addEventListener('readystatechange', event => {
 if (event.target.readyState === "complete") {
} })

And also adding the document.addEventListener('turbolinks:load', event => { //code here })

However this doesn't work when I navigate to the site I get the error.

TypeError: profileAvatarBlock is null

Not sure what could it be.

document.addEventListener('turbolinks:load', event => {
//  if (event.target.readyState === "complete") { 
  const fileUploadElement = document.getElementById('file-upload');
  console.log(fileUploadElement)

  if(fileUploadElement) {
    fileUploadElement.addEventListener('change', function(){
      const fileName = document.getElementById("post_image").files[0].name
      const fileNameElement = document.getElementById('file-name');

      fileNameElement.innerText = `${fileName}`
    })
  }

/**
 * Display the image in the file input when added to the form.
 * Replace avatar with image selected.
 */
  let profileAvatarBlock = document.getElementById('profile-avatar');

  function showImage(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        let avatarPreview = document.getElementById('profile-avatar-preview');
        let imageEl = avatarPreview.children[1]

        imageEl.setAttribute("src", e.target.result);

        ['width', 'height'].forEach(attribute => { 
          imageEl.removeAttribute(attribute)
        });

      };

      reader.readAsDataURL(input.files[0]);
    }
  }

  profileAvatarBlock.addEventListener('change', function() {
      showImage(this);
  })
//  }
});

Why is the let profileAvatarBlock = document.getElementById('profile-avatar'); returns null althought the elements exist?

    <div class="rounded-full h-24 w-24 flex items-center justify-center upload-btn-wrapper" id="profile-avatar-preview">
      <%= f.file_field :avatar, as: :file, id: "profile-avatar" %>
      <%= cl_image_tag "#{ UsersHelper::AVATAR_ADD_ICON }", width: '50', height: '50', class: 'hover:bg-transparent' %>
    </div>

The console.log from the following line also returns null on line console.log(fileUploadElement)

enter image description here

What can I do in this case? Is this a JavaScript issue or a Turbolinks issue?

Upvotes: 2

Views: 425

Answers (1)

Alex D
Alex D

Reputation: 692

It's a bit hard to figure out exactly what the problem is without being able to interact with the app, and see if the element does in fact exist. Here's a good way to try and debug this timing issue, however. Try using a MutationObserver (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) with the target node as document.

Something like the following should hopefully help with debugging this

const m = new MutationObserver((mutations, obs) => {
	for (const mut of mutations) {
  	if (mut.type === "childList" && mut.target.id === 'profile-avatar')
    	console.log(mut);
  }
});

m.observe(document, { childList: true, subtree: true });

Upvotes: 1

Related Questions