简体   繁体   English

Turbolinks:JavaScript 在 DOM 完全加载之前触发

[英]Turbolinks: JavaScript fires before DOM is fully loaded

I'm currently working on a Rails 6 application using JavaScript.我目前正在使用 JavaScript 开发 Rails 6 应用程序。 I have a file javascript/packs/posts.js which seems to be firing before the DOM has finished loading.我有一个文件javascript/packs/posts.js似乎在 DOM 完成加载之前触发。 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 })并且还添加了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类型错误:profileAvatarBlock 是 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');为什么let profileAvatarBlock = document.getElementById('profile-avatar'); returns null althought the elements exist?返回 null 尽管元素存在?

    <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)下一行中的 console.log 还在console.log(fileUploadElement)上返回null

在此处输入图像描述

What can I do in this case?在这种情况下我能做什么? Is this a JavaScript issue or a Turbolinks issue?这是 JavaScript 问题还是 Turbolinks 问题?

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 .尝试使用 MutationObserver ( https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver ) 与目标节点作为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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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