Trigger an Event in javascript before objects finish to load
I was trying to write a global JavaScriptfunction which overrides any HTML object (img
, iframe
, links and so on) before it being loaded by the page. The purpose of the overiding action was to to change the SRC
and HREF
of these objects using the DOM to any other link.
Unfortunately I didn't find any solution to that without firstly loading the object and only then changing it by the onload
event.
My second option was to change the SRC
and HREF
by matching these attributes with a regular expression and replacing the resultant values. I prefer not to do so because it's slow and consumes a lot开发者_开发问答 of time.
I would be glad if someone can share with his/her experience and help me solve this out.
JavaScript only works within the DOM.
You could however, load the page via AJAX, get the content and do any string manipulation on it.
If you are trying to modify items that exist in the static HTML of the page, you cannot modify them with javascript until they are successfully loaded by the browser. There is no way to modify them before that. They may or may not be visible to the viewer before you have a chance to modify them.
To solve this issue, there are a couple of options.
- Put CSS style rules in the page that causes all items that you want to modify to initially be hidden and then your javascript can modify them and then show them so they will not be seen before your modification.
- Don't put the items that you want to modify in the static part of your HTML page. You can either create them programmatically with javascript and insert them into the page or you can load them via ajax, modify them after loading them via ajax and then insert them into the page.
For both of these scenarios, you will have to devise a fallback plan if javascript is not enabled.
精彩评论