During the development process, I encountered the problem of integrating javascript-a for widgets in an ajax application. I use the html5-history-api library.
Here is a piece of code:
$("a").live('click', function() { history.pushState( null, null, this.href ); var urlReq = this.href; $.post( urlReq, {}, function(data){ var content = $("#content"); $("title").text(data.module.title); content.html(data.module.content); }, 'json' ); return false; });
This code loads the main content on the page. And the salt itself is this:
With a non-ajax request, the server issues the entire page, incl. and <script src = ""> </ script>. When switching from one page of the application to another, the content of the module changes, and other widgets should be loaded. For example, the text page module displays the contents of the main page and the news widget is spinning to the right. When the transition to the "news" is carried out, the publication module loads the news, and the news widget on this page is not needed. So here. If you take the situation. The news page is loaded -> click on the main one -> the text of the main one is loaded + it is necessary to load the widget that pulls the js-files behind it. There is a method:
function addScript(src){ var newScript = document.createElement("script"); newScript.src = src; newScript.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(newScript); }
And finally, the same question:
Will the following scheme be a good implementation:
On each page, add the addScript script (src) and with an ajax request do something like this:
$("a").live('click', function() { history.pushState( null, null, this.href ); var urlReq = this.href; $.post( urlReq, {}, function(data){ var content = $("#content"); $("title").text(data.module.title); content.html(data.module.content); for (var widget in data.widgets){ for(wScript in widget.scripts) addScript(wScript); } }, 'json' ); return false; });
In general, addScript () will be visible in function (data) {}?