Reputation: 974
Let's say I have some simple Javascript like:
<script>
var hello = function(){
alert("Hello World!");
}
</script>
.. on a page helloworld.html. If I loaded this script block into another page using Pjax. How do I execute the function hello()?
Upvotes: 2
Views: 2156
Reputation: 118488
This is possible with PJAX. You just need to have the script tag with type text/javascript
.
Code from PJAX library:
function executeScriptTags(scripts) {
if (!scripts) return
var existingScripts = $('script[src]')
scripts.each(function() {
var src = this.src
var matchedScripts = existingScripts.filter(function() {
return this.src === src
})
if (matchedScripts.length) {
matchedScripts.remove();
}
console.error("FOUND SCRIPTS", scripts, matchedScripts.length);
var script = document.createElement('script')
script.type = $(this).attr('type')
script.src = $(this).attr('src')
document.head.appendChild(script)
})
}
Upvotes: 1
Reputation: 85812
For security reasons, many browsers will not run Javascript injected by innerHTML
, which I'm thinking Pjax likely uses. (Here's a minimal example.)
Maybe the solution proposed in Pjax's issue #48 will help
What worked for me was to place my jQuery code in a function, call it normally on document.ready (for non-pushState browsers), and then bind the function to pjax:end, i.e.:
$('body').bind 'pjax:end', mainFunction
Upvotes: 1