1

I am using an outside API that allows me to send extra parameters inside the image src value, like so

<img src="myImage.jpg?resize=width[scrW]">

The problem is that I don't know what the width variable(scrW) is until I start loading the page. I use <script> var scrW = window.innerHtml </script> to get the width I need.

I tried using

<script> 
    document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">')
</script>

but the problem with that is that document.write displays everything in text until the document is ready (or reaches </body>). And that just looks tacky.

My question is: How can I append/prepend JS variables to src attribut values during the page rendering?

2 Answers 2

1

How about just solving the problem of the text showing up before the page renders? That's easy. Just make sure your code doesn't run until the page's HTML is completely loaded.

Vanilla JS solution:

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here
   document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
})();
</script>

Using jQuery:

<script>
$(document).ready(function() {
  document.write('<img src="myImage.jpg?resize=width['+window.innerHtml+']">');
});
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

I did have to place my API calss after the document.write, but it works :)
1

How about you give your image src some default resize value and when the page is loaded it will be updated. I have given the img an id of "myImage" so that I can access that in JavaScript code.

Here is the HTML:

<img id="myImage" src="myImage.jpg?resize=width[180]">

Insert this JavaScript at the end:

<script>var scrW = window.innerHTML;
document.getElementById("myImage").src = "myImage.jpg?resize=width["+scrW+"]";</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.