1

Sometimes I have issues while loading some ad scripts. If the external server is not responding, the whole page waits for the respond and stops loading. How can I tell those problem scripts to start executing after:

  1. The whole page is loaded.
  2. All other scripts are loaded.

3 Answers 3

1

Using defer doesn't guarantee that it will defer both loading and running. You can control exact time when you want this script to start loading and executing by adding it to page dynamically by placing <script> with following contents after everything else you want to load and run:

var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
Sign up to request clarification or add additional context in comments.

14 Comments

When does it happen that defer doesn't defer?
That looks like a solution. One more thing: how to set the script's content this way? Example: <script type="text/javascript" src="externalsite.com/script.js">var ad_id = '123abc';</script>
Well, you always can .createTextNode and script.appendChild but even without looking in specs, I'm under impression that text child of script tag is silently ignored if you specify a src attribute.
@Kos, directly from Sam's answer link: "The defer attribute gives a hint to the browser that the script does not create any content". Which is already seems like not exactly good thing. And then later: "In our tests IE4+ deferred the execution of deferred scripts, not their loading."
Also, I've quickly refreshed myself on state of defer support in different browsers and it seems that so far not all of them exactly agree what (loading/run) is deferred, for how long and if it is guaranteed at all or not. So, manual control really seems to be better solution.
|
1

Use the DEFER attribute of javascript declaration:

<script src="script.js" type="text/javascript" defer="defer"></script>

Comments

1

You need to defer your script. This will allow this rest of the page to load whilst this script is downloading.

Here is how to do it:

<script src="yourscript.js" defer="defer" type="text/javascript"></script>

More reading - http://www.websiteoptimization.com/speed/tweak/defer/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.