0

I used JavaScript in script tag in html like this:

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

With use of above code, file.js is linked to our html page. But when we add async or defer to the script tag, file.js cannot be executed in these codes:

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

Could you help me, please? Why such problem I faced with it?

In addition, for more clarifying I add a section of html comprised of file.js loading as follow:

<!DOCTYPE html>
<html lang="en-US">
 <head>

 <title>Dr.Kayvanfar</title>
 <meta charset = "UTF-8" />
 <link type="text/css" rel="stylesheet" href="Main_CSS.css" />
   
 <noscript> Your browswer don't support JS</noscript>

 </head>



 <body>
   <div id="container" style="width:1500px;margin-left:auto;margin-right:auto;color:blue;">
     <div id="header" style="height:100px;background-color:rgb(0,0,0); margin-bottom:20px;margin-top:20px; color:rgb(255,255,255);padding-top:5%">
       <span class="topheader">Future Students</span>
       <span class="topheader">Current Students</span>
       <span class="topheader">Research & Teaching</span>
       <span class="topheader">Communities</span>
       **<script src="file.js" type="text/javascript" async ></script>**
     </div>

     </body>
   
   </html>

1 Answer 1

1

It should be:

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

When to use which one:

  • If the script is modular and does not rely on any scripts then use async.
  • If script is relied on any other script then use defer.

Though you can use both:

If you specify both, async takes precedence on modern browsers, while older browsers that support defer but not async will fallback to defer.

Source

Sign up to request clarification or add additional context in comments.

7 Comments

Where is file.js located? Are you linking to it correctly?
It was linked correctly. Because it works without defer and async values. file.js and the html file are located in a same folder in my case.
That's odd. What exactly isn't working? Is any of the code from file.js running how you want it?
I write a simple code in file.js as document.write("something").
"Using document.write() after an HTML document is fully loaded, will delete all existing HTML." Is this what's happening?
|

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.