I have a little problem with asynchronous download scripts on my web page. I need to load all page scripts asynchronously. I tried many procedures that I found on google, but still this is not perfect.
Now it looks like this for me:
- Separate all scripts from layout to one package, including jquery.
- At the bottom of the page, a RenderFormat with the async tag is called.
- Now I have a problem: I need to solve a situation where scripts are rendered by @RenderFormat. The problem is that these scripts appear earlier than I need.
For example, I have this in my Home / Index file:
@Scripts.RenderFormat("<script async type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/raphael")
or simply
... $(".datapicker").datapicker(); ...
Here we get the error, "$ is not defined" because jquery is not loaded yet.
After the contents in the Layout file, I have:
... @Scripts.RenderFormat("<script async type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/frontall") ... @RenderSection("scripts", required: false)
If I take all my scripts on the page and transfer them to one package, everything will be fine, but I do not want the scripts to be displayed, I only need to do this in a specific section.
The next idea was to create a custom RenderSection method that would do the following:
function async(u, c) { var d = document, t = 'script', o = d.createElement(t), s = d.getElementsByTagName(t)[0]; o.src = u; if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); } s.parentNode.appendChild(o, s); } async("/bundles/jquery", function() {
Is there any way how to solve it? Thank you so much for your time.