V
V
Vladislav Chernushevich2015-11-13 17:40:43
JavaScript
Vladislav Chernushevich, 2015-11-13 17:40:43

How are scripts loaded?

There is such a page

<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="container"></div>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>

main.js contains code that includes scripts and styles for this page.
containerWrap = document.getElementById("container");
var jQueryMinJs = document.createElement("script");
jQueryMinJs.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
containerWrap.appendChild(jQueryMinJs);

var script__ = document.createElement("script");
jQueryUiMinJs.src = "js/script__.js";
containerWrap.appendChild(script__);

The script__.js script uses jQuery. All scripts will connect as a result of loading the page, but the console gives an error
$ is not defined
as if jQuery didn't load on the page. How to solve this problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2015-11-13
@Uladzislau

These scripts are loaded asynchronously.
Try something like this:

containerWrap = document.getElementById("container");

var jQueryMinJs = document.createElement("script");
jQueryMinJs.onload = loadOtherScripts;

jQueryMinJs.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
containerWrap.appendChild(jQueryMinJs);

function loadOtherScripts() {
  $.getScript('js/script__.js', function () {
    console.log('script__.js loaded');
  });
}

L
LinGG, 2015-11-13
@LinGG

if the scripts are declared in the document - they are loaded synchronously, since the sequence is important due to the dependence of one script on another, if they are added dynamically to the body of the document - asynchronously.
if you can’t do without a synchronous declaration, you can use onload callback, as described above.

D
Denis Vasiliev, 2015-11-13
@corvus007

And if you add jQueryMinJs.async = false;
the "Looking Ahead" Block at the end of the lesson - https://learn.javascript.ru/external-script

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question