Question

I am creating a page with multiple charts (using AmCharts), grids etc. Each chart has is own view. I noticed that when I try to link amcharts.js on each view, charts are not drawn when there are more than two charts on this page. I decided to put this link in the main page, common for all charts and they work fine, but now I cant see them by just calling action with an url. I tried to link them dynamically, like this:

     $(document).ready(function () {
if ($("#amchartsLib").length == 0) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "/Scripts/amcharts/amcharts.js";
script.id = "amchartsLib";
document.body.appendChild(script);
DrawChart(); 

Unfortunately - when firebug hits the line when I instantiate charts (new AmCharts.AmPieChart();) I get ReferenceError: Amcharts is not defined. What am I doing wrong? I can see that amcharts.js file has been properly added to the HTML document.

Was it helpful?

Solution

Looks like you may have to wait till the script file is loaded

$(document).ready(function () {
    if ($("#amchartsLib").length == 0) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/Scripts/amcharts/amcharts.js";
        script.id = "amchartsLib";
        document.body.appendChild(script);
        script.onload = function () {
            DrawChart();
        }
    }
})

OTHER TIPS

I would call the script reference in your _Layout.cshtml file (assuming that's what you're using), and then use Sections to render the other script tags. Something like this:

Layout - head (abbreviated)

<head>
    <script src="@Url.Content("~/Scripts/amcharts/amcharts.js")"></script>
</head>

Layout - bottom

@RenderSection("BottomScripts", false) // false = section not required

View (individual)

@section BottomScripts
{
   // your chart script here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top