Src error event js

Загрузка ресурсов: onload и onerror

Браузер позволяет отслеживать загрузку сторонних ресурсов: скриптов, ифреймов, изображений и др.

Для этого существуют два события:

  • load – успешная загрузка,
  • error – во время загрузки произошла ошибка.

Загрузка скриптов

Допустим, нам нужно загрузить сторонний скрипт и вызвать функцию, которая объявлена в этом скрипте.

Мы можем загрузить этот скрипт динамически:

…Но как нам вызвать функцию, которая объявлена внутри того скрипта? Нам нужно подождать, пока скрипт загрузится, и только потом мы можем её вызвать.

Для наших собственных скриптов мы можем использовать JavaScript-модули, но они не слишком широко распространены в сторонних библиотеках.

script.onload

Главный помощник – это событие load . Оно срабатывает после того, как скрипт был загружен и выполнен.

Таким образом, в обработчике onload мы можем использовать переменные, вызывать функции и т.д., которые предоставляет нам сторонний скрипт.

…А что если во время загрузки произошла ошибка? Например, такого скрипта нет (ошибка 404), или сервер был недоступен.

script.onerror

Ошибки, которые возникают во время загрузки скрипта, могут быть отслежены с помощью события error .

Например, давайте запросим скрипт, которого не существует:

Обратите внимание, что мы не можем получить описание HTTP-ошибки. Мы не знаем, была ли это ошибка 404 или 500, или какая-то другая. Знаем только, что во время загрузки произошла ошибка.

Обработчики onload / onerror отслеживают только сам процесс загрузки.

Ошибки обработки и выполнения загруженного скрипта ими не отслеживаются. Чтобы «поймать» ошибки в скрипте, нужно воспользоваться глобальным обработчиком window.onerror .

Другие ресурсы

События load и error также срабатывают и для других ресурсов, а вообще, для любых ресурсов, у которых есть внешний src .

Однако есть некоторые особенности:

  • Большинство ресурсов начинают загружаться после их добавления в документ. За исключением тега . Изображения начинают загружаться, когда получают src (*) .
  • Для событие load срабатывает по окончании загрузки как в случае успеха, так и в случае ошибки.

Такое поведение сложилось по историческим причинам.

Ошибка в скрипте с другого источника

Есть правило: скрипты с одного сайта не могут получить доступ к содержимому другого сайта. Например, скрипт с https://facebook.com не может прочитать почту пользователя на https://gmail.com .

Или, если быть более точным, один источник (домен/порт/протокол) не может получить доступ к содержимому с другого источника. Даже поддомен или просто другой порт будут считаться разными источниками, не имеющими доступа друг к другу.

Это правило также касается ресурсов с других доменов.

Если мы используем скрипт с другого домена, и в нем имеется ошибка, мы не сможем узнать детали этой ошибки.

Для примера давайте возьмём мини-скрипт error.js , который состоит из одного-единственного вызова функции, которой не существует:

Теперь загрузим этот скрипт с того же сайта, на котором он лежит:

Источник

Window: error event

The error event is fired on a Window object when a resource failed to load or couldn’t be used — for example if a script has an execution error.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

Note: Due to historical reasons, onerror on window is the only event handler property that receives more than one argument.

Event type

The event object is a UIEvent instance if it was generated from a user interface element, or an Event instance otherwise.

Читайте также:  Error 0x10 unknown returned by certverifycertificatechainpolicy

Usage notes

Unlike other events, the error event is canceled by returning true from the handler instead of returning false . When canceled, the error won’t appear in the console, but the current script will still stop executing.

The event handler’s signature is asymmetric between addEventListener() and onerror . The event handler passed to addEventLister receives a single ErrorEvent object, while the onerror handler receives five arguments, matching the ErrorEvent object’s properties:

A string containing a human-readable error message describing the problem. Same as ErrorEvent.message .

A string containing the URL of the script that generated the error.

An integer containing the line number of the script file on which the error occurred.

An integer containing the column number of the script file on which the error occurred.

The error being thrown. Usually an Error object.

Note: These parameter names are observable with an HTML event handler attribute, where the first parameter is called event instead of message .

Источник

.error()

.error( handler ) Returns: jQuery version deprecated: 1.8, removed: 3.0

Description: Bind an event handler to the «error» JavaScript event.

version added: 1.0 .error( handler )

version added: 1.4.3 .error( [eventData ], handler )

Note: This API has been removed in jQuery 3.0; please use .on( «error», handler ) instead of .error( handler ) and .trigger( «error» ) instead of .error() .

The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

For example, consider a page with a simple image element:

The event handler can be bound to the image:

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Handler for .error() called.

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

Note: A jQuery error event handler should not be attached to the window object. The browser fires the window ‘s error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

Additional Notes:

  • As the .error() method is just a shorthand for .on( «error», handler ) , detaching is possible using .off( «error» ) .

Example:

To replace all the missing images with another, you can update the src attribute inside the callback passed to .error() . Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.

Источник

JavaScript Resource Loading: onload and onerror

The browser helps to track the loading of external resources, such as pictures, scripts and more.

Two primary events are used for that purpose:

  • onload : it supposes a successful load.
  • onerror : it means that an error has occurred.

Loading a Script

Imagine that you should load a third-party script and call a function residing there, as illustrated below:

To run the function declared inside that script, you should wait until the script loads and only then call it.

Please note, that here you could also use JavaScript modules, but they are not widely used by third-party libraries.

Script.onload

The load event is the main helper here. It occurs once the was already loaded and executed.

Читайте также:  Smart drive error codes

Here is an example of the load event:

So, Script variables and run functions can be used in download.

But, the loading may fail. Note that there isn’t any such script (error 404) or the server is done.

Let’s see what happens in such a circumstance.

Script.onerror

Errors occurring during the script loading are tracked in an error event.

Let’s take a look at an example of requesting a non-existing script:

Please, take into account that the details of the HTTP error are not available here: you can’t know whether it’s an error 404, 500 or anything else.

Another important thing to note: the onload and onerror events track only the loading itself. In other words, errors occurring during the script processing and execution are out of the framework. So, if a script loaded efficiently, then onload happens, even if it includes some programming errors. For tracking the script errors, you can use a global handler called window.onerror .

Other Resources

The load and error events operate for any other resources that have an external src, like in the example below:

But, note that several resources begin loading once they are added to the document. The is an exception to the rule. It begins to load after getting a src (*) .

For , the iframe.onload event occurs once the iframe loading is over. It is both for the efficient load and in case of an error.

Crossorigin policy

Scripts from one site don’t have access to the scripts of the other one. For example, a script at https://www.instagram.com/ can’t read the user’s mailbox at https://gmail.com.

In other words, one origin (domain/port/protocol) can’t access the content of the other one. Even in case of having a subdomain, these are considered different origins.

The rule above affects the resources from other domains, as well. An example of a script error.js consisting of a single (bad) function call is demonstrated below:

If you try loading it from the same site where it’s located, you will have this:

A good error report can be seen here:

The example of loading the same script from another domain will look like this:

So, there is a different report here:

There can be different details, depending on the browser. However, idea remains the same: any information regarding the internals of a script is hidden. The reason is that it is from a different domain.

Still, it is important to know details about errors.

Источник

Tracking Image Error Events Using Event Delegation In JavaScript

At InVision, the primary asset is the Image. On the server-side, we know everything about these images: size, density, orientation, how long it takes to resize them, and whether or not they can even be thumbnailed properly. On the client-side, however, we don’t do a lot of active tracking for images. This is something I’ve been thinking about changing. There are a number of ways in which image tracking can be added to a client-side application. For example, event-delegation. Now, the «error» event, emitted by a failed IMG object, doesn’t bubble up in the DOM (Document Object Model). But, it does participate in the Capturing phase. Which means, we can use event delegation to capture image error events at the top of the DOM tree.

When an event is fired on the DOM (Document Object Model), the browser determines the «propagation path» of the Event object through the DOM tree. The browser then passes the Event object through three different phases:

  • Capture Phase
  • Target Phase
  • Bubble Phase
Читайте также:  Ошибка при обновлении по sony

All events pass through the Capture phase; but, only some events have a Target phase handler defined; and, only some events enter the Bubble phase (either by default or because their bubbling has been canceled). Error events, such as those emitted by a failing IMG object, are among the Events that don’t enter the Bubble phase. This means that we can’t use event-delegation to handle IMG error events during Bubbling. But, we can still use event-delegation to handle IMG error events during the Capture phase.

ASIDE: In React.js, IMG error events can be handled using event-delegation because React uses a synthetic event system where all events are transparently handled using event-delegation. As such, even events that don’t bubble natively in the browser can be treated as if they bubble inside a React application.

In order to add an event handler for the Capture phase of a DOM event, we need to pass in the optional third argument to the .addEventListener() method:

Element.addEventListener( eventType, handler, true )

The «true» parameter, in this .addEventListener() call, tells the browser to attach the given event handler to the Capture phase, not the Bubble phase. This means that this event handler will see the events as they are propagating down to the target object, regardless of whether or not they ever bubble back up through the DOM.

To see the capturing of IMG error events, I’ve put together a small demo in which you can load one of two groups of images: working and failing. The «working» images will all result in 200 OK response, which we ignore. And, the «failing» images will all result in a 404 Not Found response, which we will capture in our event-delegation handler.

In the following code, notice that I’m using the «true» parameter when configuring my handleErrorCapture() event-handler:

As you can see, I’m attaching the handleErrorCapture() event-handler to the BODY element using the Capture phase. If we open this up in the browser and attempt to load the failing images, we get the following page output:

As you can see, each of the five images in the «failing» group emitted an Error event. And, each of the five emitted events was successfully observed on the BODY Element as the Error event propagated down to the Target object during the Capture Phase. In this way, even though the Error objects never bubble back up, we can still view and record them in a single point in the DOM tree using event-delegation.

When it comes to handling events on the DOM (Document Object Model), I generally use the Target phase or the Bubble phase. Literal years go by without me even thinking of the Capture phase. But, in some cases, like observing IMG error events, the Capture phase is what makes event-delegation possible.

A Note On The Phrase: «Event Delegation»

When I say «event delegation» in this context, what I mean is that we have one event handler listening for events triggered by a dynamic number of Elements located farther down in the DOM tree. Though, to be fair, «event delegation» may not be the most accurate term since we’re not really handling the event for the Target; rather, we’re simply «observing» the event emitted by the target. That said, the gesture is similar and the phrase is one people are comfortable with. As such, it feels like a reasonable phase to use for this context.

Want to use code from this post? Check out the license.

Источник

Smartadm.ru
Adblock
detector