0

My Chrome seems to be doing something weird with the execution of scripts.

Code:

<!DOCTYPE html>
<html>
<head>
    //Metadata
</head>
<body>
    //Page Content
    <script type="text/javascript" src="somescript.js"></script>
</body>
</html>

In Firefox, the script executes after the page content has loaded, as expected. However, in Chrome, the script seems to execute before the page content has loaded, freezing the loading in the meanwhile (I tested this using prompt() - page refuses to load until it is resolved).

What is the reason of this behavior and can it be fixed? I am on Chrome version 63.0.3239.132.

  • Maybe you're getting a blank page because it hasn't closed the body and html tags yet idk – Phiter Jan 11 '18 at 16:06
  • Try this https://www.w3schools.com/jsref/event_onload.asp – croraf Jan 11 '18 at 16:10
  • I think you'll find [this answer](https://stackoverflow.com/a/24070373/4760460) helpful. It's about using `async` and `defer` on your `scripts`. – Anthony Jan 11 '18 at 16:10

1 Answers1

2

Injected scripts that use the src-attribute are executed asynchronously in chrome. This is because generally this way is used to include script files, that contain method definitions / classes etc - not a self starting execution.

To ensure it works as expected, either include the code directly in script tags:

<body>
    //Page Content
    <script type="text/javascript">content of somescript.js</script>
</body>

Or wrap the execution into a method inside that file, which you can either execute using (if you have jquery)

$( document ).ready(function() {
    doTheThingFromScript();
});

or old fashion

<body onload="doTheThingFromScript()">

In both cases, you should move the inclusion of the scriptfile into the head-part of your website.

dognose
  • 20,360
  • 9
  • 61
  • 107