Медленная загрузка страницы из-за событий onclick в html-якорях - PullRequest
3 голосов
/ 02 марта 2011

Мы столкнулись со странной проблемой, с которой мы пытаемся добраться до сути.

У нас есть веб-система, а на рассматриваемой странице есть таблица с 600 строками.В каждой строке есть две опции «блокировать / разблокировать» и «редактировать», которые реализованы в виде двух якорей с событиями onclick.События onclick определены в html и не связаны jquery - это потому, что каждый вызов javascript различается в зависимости от идентификатора записи, например, unlock (132);

Эта страница занимает от 10 до 25 секунд.сделать в Internet Explorer, но в Chrome отображает мгновенно.Наши клиенты поддерживают только Internet Explorer!: (

Это то, что я обнаружил, и я надеюсь, что кто-то сможет объяснить, что происходит, или объяснить причину возникновения проблем:

  1. Если я переместуjavascript-вызовы из onclick и размещение внутри href, страница загружается мгновенно - почему это может иметь какое-то значение?

  2. Если я заменю мои вызовы javascript на alert ('');Атрибут) страница загружается мгновенно 2a. Поэтому я перевел свои javascript-вызовы обратно, но заменил функции пустыми заглушками, и страница все еще загружалась медленно. Это странно, потому что теперь я понятия не имею, что делает Internet Explorer !!

Кто-нибудь слышал о чем-то подобном или дал хорошее объяснение происходящему?

С наилучшими пожеланиями, Мэтью

Ответы [ 4 ]

4 голосов
/ 02 марта 2011

Трудно сказать, почему проблема возникает, не видя живой пример. В прошлом я видел подобные проекты, в которых у IE6 были очень серьезные проблемы с производительностью, когда хендеры динамически связаны с якорями в больших таблицах. Но не тогда, когда они были жестко закодированы в html.

Один из способов решения этой проблемы - захват событий клика один раз на более высоком уровне в DOM и затем определение привязки источника. Если вы используете jQuery (> = v1.4.2), вы можете реализовать это довольно быстро, используя делегат .

Если в html есть следующие якоря (примечание: атрибут data-id будет подтвержден с html5 doctype ):

<td>
    <a href="#" class="lock" data-id="123">Lock/Unlock</a>
    <a href="#" class="edit" data-id="123">Edit</a>
    ... data ...
</td>   

В вашем js добавьте делегат события click, который сработает для всех якорей в таблице. Затем вы идентифицируете привязанный якорь по его идентификатору данных и вызываете любую нужную вам функциональность:

$('table').delegate('a', 'click', function() {
    var el = $(this)
        id = el.attr('data-id');

    if (id && el.hasClass('lock')) {
        alert('Lock/unlock ' + id);
        // do stuff...
    }
    if (id && el.hasClass('edit')) {
        alert('Edit ' + id);
        // do stuff...
    }
});

Преимущество использования делегата состоит в том, что при динамическом изменении содержимого таблицы обработка событий будет работать для вновь созданных якорей. Например, допустим, вы решили добавить нумерацию страниц в таблицу, в которую новые данные загружаются с помощью ajax.

ОБНОВЛЕНИЕ:

На основе комментариев добавлен пример http://jsfiddle.net/johnhunter/QKYJ5/, который использует параметры строки запроса для передачи данных делегатору. Это удерживает js от html и может послужить основой для резервного копирования без сценариев.

1 голос
/ 02 мая 2012

Я узнаю, что трудный путь.Связывание событий элементов с использованием js, когда документ готов, очень и очень медленно для страниц с большим количеством элементов.Не говоря уже о рендеринге HTML с помощью js (после вызова ajax я должен был обновить свою страницу с новой информацией, но мне пришлось заново визуализировать всю страницу на случай, если появятся новые данные для других частей страницы).Время ожидания моей страницы истекло.Это IE для тебя.Поэтому я решил использовать встроенную привязку событий и заново загружать страницу после каждого события.

0 голосов
/ 21 марта 2019

Это сработало для меня:

$(document).ready(function(){
    $( "a.scrollLink" ).click(function( event ) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>
<div>
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.
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.
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.
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.
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.
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.
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.
</div>
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>

Эту статью вы можете найти в оригинале здесь .

0 голосов
/ 30 июля 2012

@ Мэтью Привет, я тоже столкнулся с точно такой же проблемой. У меня была функция сценария Java, которая принимает два параметра и была связана с событием onclick на теге привязки. Это замедляло время загрузки страницы в IE.

Решение: Используйте jQuery для привязки события onclick вместо onclick внутри тега привязки. Вы можете использовать регулярные выражения для поиска якорных элементов. Используйте следующий код в document.ready (), как показано ниже:

$(document.ready(function(){

$("a[id^=elemID]").click(function(){

//Your call to the javascript function. 

   });

});

Это определенно решит вашу проблему.

Привет

...