【问题标题】:Turbolinks: JavaScript fires before DOM is fully loadedTurbolinks:在 DOM 完全加载之前触发 JavaScript
【发布时间】:2020-04-18 00:06:41
【问题描述】:

我目前正在使用 JavaScript 开发 Rails 6 应用程序。我有一个文件javascript/packs/posts.js,它似乎在 DOM 完成加载之前就被触发了。我已经尝试了以下没有运气。

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

同时添加document.addEventListener('turbolinks:load', event => { //code here })

但是,当我导航到我收到错误的站点时,这不起作用。

TypeError: profileAvatarBlock 为空

不知道会是什么。

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

为什么let profileAvatarBlock = document.getElementById('profile-avatar');虽然元素存在却返回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>

下一行的console.log 也返回nullconsole.log(fileUploadElement)

在这种情况下我该怎么办?这是 JavaScript 问题还是 Turbolinks 问题?

【问题讨论】:

标签: javascript turbolinks ruby-on-rails-6


【解决方案1】:

在无法与应用交互的情况下准确找出问题所在,并查看该元素是否确实存在,这有点困难。但是,这是尝试和调试此计时问题的好方法。尝试使用 MutationObserver (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver),目标节点为document

以下内容有望帮助调试此问题

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

【讨论】:

  • artsyspace-test.herokuapp.com 这里是网站。 id 在另一个模板中,但它仍然不应该返回 nil
  • 我提供的代码将帮助您确定 何时 id profile-avatar 的元素在 DOM 上可用。
猜你喜欢
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多