Два вероятных случая могут генерировать данное сообщение в консоли браузера.
Раннее обращение к js плагину
Те или иные свойства могут быть недоступны, если вы обращаетесь к методам и свойствам до того как они определены. В данном случае обращение к свойству $.browser.msie происходит до полной готовности jQuery.
Решение простое — оберните ваш код в реализацию события ready.
//я использую рекомендуемую в доках api.jquery.com вариацию: $( function () { //ваш код }) |
Использование версии jQuery > 1.9
Если вы используете версию jQuery выше 1.9, то свойства jQuery.browser там просто нет, т.к. оно считается устаревшим, начиная с версии 1.3, а в версии 1.9 было удалено из библиотеки.
Никто не мешает его добавить самостоятельно.
<script type=«text/javascript» src=«jquery-YOUR-VERSION.min.js»></script> <script type=«text/javascript»> //один из примеров реализации jQuery.browser jQuery.browser = {}; (function () { jQuery.browser.msie = false; jQuery.browser.version = 0; if (navigator.userAgent.match(/MSIE ([0—9]+)./)) { jQuery.browser.msie = true; jQuery.browser.version = RegExp.$1; } })(); </script> |
Есть более комплексное решение в виде скрипта миграции. Там учитываются многие ушедшие в историю свойства и методы jquery, помогая вебмастерам пользоваться старыми скриптами.
Просто подключите его как один из плагинов jQuery.
Страница проекта на github — https://github.com/jquery/jquery-migrate
Написать комментарий
Данная запись опубликована в 13.04.2017 16:57 и размещена в jQuery.
Вы можете перейти в конец страницы и оставить ваш комментарий.
Мало букафф? Читайте есчо !
Проверка checkbox состояния checked, jQuery
Февраль 19, 2020 г.
Шаблон для проверки состояния элемента input[type=’checkbox’]. Код проверяет отмечен элемент или нет.
[crayon-648858b588038241442812/]
Проверка выполняется с помощью метода is(), который читает в данном случае не атрибуты тега input, а именно …
Читать
Делаем эффект параллакса для заднего фона на сайте
Октябрь 19, 2015 г.
Очень простая мулька, но выглядит при соответствующем фоне потрясающе. Сделаем так, чтобы при скроллинге страницы, фон двигался вдвое медленнее, создавая что то вроде эффекта параллакса.
Этот кусочек скрипта привязывает нас к событию onscroll окна. …
Читать
See this issue mainly rises due to browser navigation and version properties.
For this you have to add just following code in function :
/* solution to undefined msie */
jQuery.browser = {};
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
/* solution to undefined msie */
For exapmle I am using it on click function, see it:
$(document).on('click', '.remove_add_test', function() {
var product_id = $(this).data('id');
var thisproduct = $(this);
/* solution to undefined msie */
jQuery.browser = {};
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
/* solution to undefined msie */
jConfirm('Are you sure you want to delete record?', 'Remove Product', function(r) {
if (r == true) {
$.ajax({
type: 'POST',
url: 'scripts/ajax/index.php',
data: {
method: 'removeproduct_fromcart',
id: product_id
},
dataType: 'json',
success: function(data) {
if (data.RESULT == 0) {
$(".price span").text(data.totalprice);
$(thisproduct).closest('tr').remove();
$(".cart-number").text(data.productcount - 1);
$.growl.notice({
title: "Shopping Cart",
message: data.MSG
});
location.reload();
// window.location.href = 'https://www.youth-revisited.co.uk/payment.html';
}
// window.location.href = 'https://www.youth-revisited.co.uk/payment.html';
}
});
// window.location.href = 'https://www.youth-revisited.co.uk/payment.html';
} else {
return false;
}
});
});
If you have ever dealt with JavaScript in a web project, you might have encountered the dreaded «Uncaught TypeError: Cannot read property ‘MSIE’ of undefined» error. This error occurs when a script attempts to access the MSIE
property of an undefined object. The good news is that this issue is fairly easy to fix once you understand what’s causing it. In this guide, we’ll discuss the root cause of the problem and provide step-by-step instructions on how to resolve it.
Table of Contents
- Understanding the Problem
- Step-by-Step Solution
- FAQ Section
- Related Links
Understanding the Problem
The 'Cannot read property MSIE of undefined'
error typically occurs when a script tries to access the MSIE
property of the jQuery.browser
object. This object was deprecated in jQuery 1.3 and removed completely in jQuery 1.9. If you’re using a version of jQuery later than 1.9, the jQuery.browser
object will not be available, resulting in the error.
This error often arises when using older plugins or scripts that rely on the jQuery.browser
object to detect the browser being used by the visitor. Since this object is no longer available in newer versions of jQuery, the script throws an error when trying to access the MSIE
property.
Step-by-Step Solution
To fix the 'Cannot read property MSIE of undefined'
error, follow these steps:
Identify the problematic script or plugin: The first step is to identify which script or plugin is causing the error. You can do this by checking your browser’s console for error messages and looking at the stack trace to determine the source of the error.
Update the problematic script or plugin: If an updated version of the problematic script or plugin is available, replace the old version with the newer one. The updated version should be compatible with your current version of jQuery and no longer rely on the jQuery.browser
object.
Revert to an older version of jQuery: If an updated version of the problematic script or plugin is not available, consider reverting to an older version of jQuery (1.8.3 or earlier) that still includes the jQuery.browser
object. Keep in mind that this may cause compatibility issues with other parts of your project that require a newer version of jQuery.
Use the jQuery Migrate plugin: If reverting to an older version of jQuery is not an option, you can use the jQuery Migrate plugin to restore the jQuery.browser
object. This plugin can be used alongside newer versions of jQuery to provide compatibility with older scripts and plugins that rely on deprecated features.
Modify the problematic script or plugin: If none of the above solutions is suitable, you can manually modify the problematic script or plugin to remove the dependency on the jQuery.browser
object. This may involve replacing the browser detection code with a more modern approach, such as using feature detection or the Browser Detection library.
FAQ Section
Why was the jQuery.browser
object removed from jQuery?
The jQuery.browser
object was removed from jQuery because it encouraged browser sniffing, which is generally considered a bad practice. Instead, developers are encouraged to use feature detection, a more reliable and future-proof method of determining browser capabilities.
What is feature detection, and how is it different from browser detection?
Feature detection is a technique used to determine whether a browser supports a specific feature or not, without relying on the user agent string. This is in contrast to browser detection, which relies on analyzing the user agent string to determine the browser in use. Feature detection is considered more reliable and future-proof than browser detection, as user agent strings can be easily spoofed or misrepresented.
How do I use the jQuery Migrate plugin?
To use the jQuery Migrate plugin, simply include it in your project after the jQuery library. It will automatically provide compatibility for deprecated features, such as the jQuery.browser
object. You can download the plugin from the official jQuery Migrate GitHub repository.
Can I use the jQuery Migrate plugin with any version of jQuery?
The jQuery Migrate plugin is designed to work with specific versions of jQuery. There are two versions of the plugin available:
- jQuery Migrate 1.x: For use with jQuery 1.9.x to 1.12.x
- jQuery Migrate 3.x: For use with jQuery 3.0.x and later
Make sure to use the appropriate version of the plugin for your project.
Is there a performance impact when using the jQuery Migrate plugin?
Using the jQuery Migrate plugin may have a slight performance impact, as it adds additional code to your project to provide compatibility for deprecated features. However, this impact is generally negligible and should not cause any significant performance issues.
- jQuery Migrate Plugin
- Browser Detection Library
- MDN — Feature Detection
Совершенно случайно зашел на клиентский сайт, статью добавить…и обнаружил, что почему-то мой colorbox не хочет работать.
Оказалось, что при инициализации скрипта jquery colorbox возникает ошибка:
Cannot read property ‘msie’ of undefined (browser.msie).
Решение оказалось простым..на одном из форуумов кто-то написал, что возможно каким-то образом colorbox грузится раньше, чем готова jQuery,
Так вот проблема решилась таким образом:
Код colorbox’а помещаем в следующее событие
jQuery(document).ready(function(){ });
Это всё..в общем то и новичку понятно, что мы сделали…теперь не будет ошибки msie of undefined))
Мои контакты →
Похожие записи
- JQuery динамически изменить meta теги, реально?
- Свой текст кнопки “Мне нравится” Вконтакте. Динамический контент.
- Вылет блока за край экрана на jQuery
© 2006 — 2023, Александр Сергеев
jQuery BBQ hasn’t been updated for quite some time. It appears to use the $.browser method, but that has been removed as of jQuery 1.9. There’s a quick workaround:
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();
</script>
<script type="text/javascript" src="jquery.ba-bbq.min.js"></script>