Avoid jQuery (pre)loading images - javascript

I have a string of HTML that I use as jQuery input document.
// the variable html contains the HTML code
jQuery( html ).find( 'p' ).each( function( index, element ) {
// do stuff
});
Though, I keep getting errors that the images doesn't exist (in my variable html). The images in the HTML have relative URL's which doesn't correspond to images on my host, so naturally, they can't be found so I get 404 errors in my console.
Is there a jQuery-way to avoid jQuery loading the images? If not, I'll have to find all images and replace the src using non-jQuery which is a bit sad because that's exactly where jQuery comes in handy :p
Edit:
I'll explain step by step.
I have a variable, html, that contains some HTML code from another site. I put that variable in the jQuery constructor, because I want to perform actions on that HTML.
jQuery( html );
At this point I get 404 errors because the images in the HTML source are relative; they don't correspond to the images I have on my host.
I can't use jQuery to remove the src tag, because I still get errors
Writing a bit of javascript to modify the src value is plain silly; this is why I use jQuery
So, again, all I'm asking is if there's a setting or whatever that avoids jQuery from loading the images in the supplied source.
Thank you.

To stop images loading you need to modify html before creating jQuery( html ) object. You can use jquery for that also.
var newhtml = html.replace('src=','nosrc=');
jQuery( newhtml ).find( 'p' ).each( function( index, element ) {
// do stuff
});

right after you get the html - replace the src to something else ()maybe to your own picture [global url]. ( simple string replace)
this will help you not to get the 404 - not found error in the console.
also you can make the html as jQuery - and set all the $("img") with your SRC or remove it if you want.
tell me if thats what you after.
edit
what about
$("img").removeAttr("src");
edit2
string html = #"
<h1>
<img src="" ... >
</img>
<img></img>-bad
<img/>-bad
<img src="" ... />
</h1>";
string result = Regex.Replace(html, #"<img\s[^>]*/>", "", RegexOptions.IgnoreCase);

Related

load an svg from server and show it into an html element

I have tried to load an svg from server and show it into an html element using jQuery like as follows,but it does not show the svg,what is wrong with this code?
I know it can show using <img> tag,but i need to write some events on the svg elements.
$.get( "http://example.com/_assets/img/gptest.svg", function( data ) {
$( "#svg-main" ).append( data );
});
<div id="svg-main"></div>
Why don't you just add an img-tag?
<img src="http://example.com/_assets/img/gptest.svg">
If you want to add it via jQuery do it like this:
$('#svg-main').append('<img src="http://example.com/_assets/img/gptest.svg">');
Here is a handy article about svg.
Basically you need to define width nad height in order ot display svg image.
So that's probably why it is not displaying in your case.

JavaScript for auto embedding image URL works but getting W3 errors

I now where my errors are, I just don't know enough about javascript know where it needs to go, can anyone help me. I finally got this all working to auto embed media and images on my site (phpbb forum), and it works good, but the image embed isn't correct (even though it does work).
Here's my errors from W3:
required attribute "src" not specified
required attribute "alt" not specified
document type does not allow element "img" here
end tag for "img" omitted, but OMITTAG NO was specified
So obviously I did a number on the code, but somehow it's managing to function.
Here's my hack job of a code, can anyone help me clean this mess? (I'm just a newbie, this was the best I could come up with after hours and hours);
<script type="text/javascript">
(function ($) {
$(document).ready(function () {
$(".content1 .postlink").oembed(null, {embedMethod: "append", maxWidth: 300,});
});
})(jQuery);
$(document).ready(function () {
var href = $('a.postlink.img-link').get(0).href;
$('a.postlink.img-link').html($('').attr('src', href).fadeIn(1000));
$('a.postlink.img-link').colorbox({rel: 'img-link'});
})
</script>
This fixed it.
<script type="text/javascript"> //<![CDATA[
// [your script here]
// ]]></script>
Your code could use some tidying up, but we would need to see the relevant HTML to really help you tidy it up.
You probably want to change
$('a.postlink.img-link').html($('').attr('src', href).fadeIn(1000));
to
$('a.postlink.img-link img').attr('src', href)
as a start.
However, to answer your main question about the W3 validator, looks at the page before any javascript has run. So I am assuming that you have <img> tags with no src attribute (looks like this is getting set by the javascript). These are the sort of errors that the validator is complaining about.
A HTML page should really 'work' correctly even if javascript is disabled. Even if this just means showing placeholder content or a message saying that javascript is required.
To fix the validation errors, add src and alt attributes to the img tags in your html, point them at some sort of placeholder images and text that is representative of the actual content that will be replaced by your JS.
This should also help in the visual rendering of your page.

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

After injecting html, a cached jQuery selector gives different result from non-cached selector

Found the solution! Don't bother creating an answer
Turns out I was injecting the html twice - once before creating the selectors, and then, due to some unfinished refactoring, a second time; thus overwriting the relevant parts of the DOM. The cached selectors were still referencing the old DOM part, though, and so kept it from being garbage collected. Changing the old part had, of course, no impact on the newer parts, something that was clearly shown by making jQuery do the selection anew.
Question
I am in the process of trying to create a widget. After running its script, the widget finds a with a certain code tag (referenced as $rootElem below), downloads a piece of html code and injects it into this div. After doing this, it starts attaching events to input elements, building ui elements like sliders, etc.
AFAIK, after injecting html into the DOM, the resulting DOM should be equivalent to just having the html there to begin with. Turns out that jQuery thinks otherwise. Just to be specific, I am first injecting the html, and second starting to find and cache selector results.
The following to code blocks should be equivalent (do the same thing); change a piece of html like <span>awaiting calculation ...</span> into something like <span>1234</span>. And, lo and behold, if I put all the html into the same document (not injecting it), they actually are doing the same thing.
Caching the selector result for later retrieval
var $result = $rootElem.find( "div.result p:nth-of-type(1) span" );
$.subscribe( "/server/calculateLoan/finished", function ( e, firstPayment ) {
$result.text( firstPayment ) );
} );
Doing the selection every time
$.subscribe( "/server/calculateLoan/finished", function ( e, firstPayment ) {
$rootElem.find( "div.result p:nth-of-type(1) span" ).text( firstPayment ) );
} );
But if I move the widget's html code out of the main document, and inject it before working on it, only the non-cached (latter) version works. Actually the first one also seems to work. If I set a break point in the anonymous function I can see a weird thing happening:
> $result.text()
<span>awaiting calculation ...</span>
> $rootElem.find( "div.result p:nth-of-type(1) span" ).text()
<span>awaiting calculation ...</span>
> $result.text("1234") //This is not showing in the browser window!
[<span>1234</span>]
> $result.text() //This is not showing in the browser window!
[<span>1234</span>]
> $($result.selector).text() //What kind of magic is this?!
<span>awaiting calculation ...</span>
> $rootElem.find( "div.result p:nth-of-type(1) span" ).text()
<span>awaiting calculation ...</span>
It seems as if the cached jQuery selector points to another DOM element (whose changes are not shown) than if I search for the same element. And this only happens when injecting the html, not when the widget's html has been copy-pasted into the page. Anyone cares to explain what is happening?
This happens in both Chrome and Firefox.
The html bit on the main page looks like this:
<div id="widget_calculator"><!-- dynamic fetch --> </div>
The widget's html
<h1>Widget calculator</h1>
<div class="user-inputs">...</div>
<div class="result">
<p><span>awaiting calculation ...</span></p>
</div>
The code that injects the html
function fetchHtmlTemplate( templateUrl ) {
// set globals
$ = jQuery;
$rootElem = $( "#widget_calculator" );
$.get( templateUrl, function ( htmlTemplate ) {
$rootElem.html( htmlTemplate );
buildWidget();
} );
}

Parse and handle DOM that came as a string input

Here is the thing,
I have a textarea (with ID "input_container") full of HTML code, the simple example is:
<!doctype html>
<html>
<head></head>
<body>
the other place
</body>
</html>
How can I parse it and use it in jQuery as a legitimate DOM?
For example, to do
$(varWithDom).find(...)
with that DOM?
What I already tried
I tried to parse it using jQuery but a funny thing happened - jQuery removed the DOCTYPE and all of the HEAD, and left me with nothing but
the other place
My original method is here: jQuery HTML parser is removing some tags without a warning, why and how to prevent it?
I never found a solution yet. Any ideas? might this be a bug on jQuery or what?
If you need the entire content as elements, you might try using an iframe.
// create and append new iframe
var iframe = document.createElement('iframe');
document.documentElement.appendChild(iframe);
// set its innerHTML
iframe.contentWindow.document.documentElement.innerHTML = varWithDOM;
// grab the `window`
var win = iframe.contentWindow;
// remove the iframe
document.documentElement.removeChild(iframe);
Demo that grabs the head: http://jsfiddle.net/K6tR2/
original answer
It isn't so much jQuery removing it as it is the browser. This behavior will vary in different browsers.
One thing you might try would be to place the entire thing in a <div>, so that becomes your context...
$('<div>' + varWithDom + '</div>').find(...)
Now it won't really matter what is stripped away (unless you actually needed something in the <head>), because it will all be descendant of the outer div.
If you didn't want that, then you'd need to do your query twice, once with .find(), and once with .filter()...
var els = $( varWithDom );
var links = els.find( 'a[href]' ).add( els.filter( 'a[href]' ) );

Categories

Resources