Прокрутка окна jQuery не работает без предупреждения

Приведенный ниже демонстрационный код отлично работает при загрузке страницы. Но когда я пытаюсь реализовать на живом веб-сайте, он не работает без alert(). Я проверил в консоли, на сайте не было ошибок.

Активная ссылка на веб-сайт здесь.

$(window).on("load", function() {	
//alert();
$('html,body').animate({scrollTop:500},800);
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</div>

Где находится тег script в вашем html-файле?

Clive Machado 13.05.2019 07:07

@CliveMac внизу попробуйте найти 800 вы можете найти.

Saravana 13.05.2019 08:01
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
61
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Похоже, вы пытаетесь прокрутить вниз, когда страница загружается.

Попробуйте использовать:

$(document).ready(function() {
  $('html,body').animate({scrollTop:500},800);
});

Вы пытались добавить его в конец файла main.js непосредственно перед последней строкой? Или вы добавляете его через CMS?

ashmatty 13.05.2019 06:46

Добавьте класс к элементу body только для этой страницы и укажите этот класс в своем вызове jQuery для анимации.

ashmatty 13.05.2019 06:52

Заголовок будет общим для всей страницы. я не могу расстаться

Saravana 13.05.2019 06:58
Ответ принят как подходящий

Причина этого в том, что когда вы загружаете ресурсы с удаленного сервера, загрузка занимает некоторое время по сравнению с локальным.

Когда вы добавляете предупреждение вверху, DOM получает дополнительное время для загрузки до выполнения вашего кода.

Решение:

  1. Поместите свой скрипт (который не работает) после тега </body>. Затем он выполняется после анализа всех элементов тела.

<html>
  <body>
    Your HTML body
  </body>
  <script>
    $(window).on("load", function() {	
    //alert();
    $('html,body').animate({scrollTop:500},800);
    });
  </script>
  
</html>

или

  1. Use $(document).ready() instead

    или

  2. Use setTimeout()

setTimeout(function(){
  $(window).on("load", function() {	
	//alert();
	$('html,body').animate({scrollTop:500},800);
	});
}, 50);

Хорошее объяснение можно найти на https://eager.io/blog/how-to-decide-when-your-code-should-run/

могу добавить с некоторым примером. я не понимаю пример

Saravana 13.05.2019 06:57

Я добавил несколько примеров в свой ответ. Надеюсь это поможет!

Arosha 13.05.2019 07:07

Не работает бро. Я думаю, что некоторые из моих других скриптов игнорируют прокрутку. Я не знаю, какой это

Saravana 13.05.2019 07:59

Кстати, я проверил ваш сайт, и анимация сработала! Я использовал Chrome и воссоздал "if (viewportWidth < 767) {$('html,body').animate({scrollTop:310},800);}"

Arosha 13.05.2019 08:38

Ok. я проверю

Saravana 13.05.2019 08:59

Другие вопросы по теме